1

is it true that if you declare variable as constant it doesn't take up a memory slot? If so how does it work?

I don't remember where I read this but I can't find any info about it anywhere.

Thanks

2 Answers 2

3

Yes, it's true. The documentation says this:

The compiler does not reserve a storage slot for these variables, and every occurrence is replaced by the respective value.

This variables are put in the compiled code (like constants) and each occurence of this variables and its value is known. In fact, if you see the compiler code there is a instruction like this:

PUSH <constant_value>

that loads the constants value in advance.

More information here.

0
0

sometimes you have a state variable that you know that it will never change

  • in this case its better to declare this variable as a constant rather than as a regular state variable

  • by declaring a state variable as constant you will be able to save Gas when a function is called that uses that state variable

  • the main benefit of declaring a state variable as constant is that you will be able to save gas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.