Home > Software design >  How are local constant variables treated in C programming
How are local constant variables treated in C programming

Time:11-22

I've been messing around with Rust and the immutable variable idea is interesting to me. so I've been using it in my C programs as well. But now I'm wondering if there is any difference in a local variable that is defined with the "const" keyword and one that isn't.

I assume both are still put on the stack so there is no difference? other than the fact that it cannot be modified after declared and initialized obviously.

CodePudding user response:

I assume both are still put on the stack so there is no difference? other than the fact that it cannot be modified after declared and initialized obviously.

In general, it's not safe to assume that either will be assigned storage on the stack, but indeed, const is not a discriminator in that regard.

The primary effect of const is to signal programmer intent and provide for the compiler to recognize violations of that intent.

For local variables whose addresses are never exposed outside the innermost block in which they are declared, that's about the extent of it, provided that the program indeed does not violate that intent. For such objects, the compiler does not need help from const to recognize or make use of their unchangingness.

On the other hand, where the address of a const object is exposed outside the scope in which that object is declared, const-correctly, the compiler may rely on the object indeed not being modified via that address or another derived from it. For example, that could make some optimizations possible that would not otherwise be safe.

Overall, I guess the take-home is that const does not convey a difference in form, but rather one in allowable function. The compiler may produce different messages and different binaries for sources that are the same but for one or more appearances of const -- but it also might not. It depends on the compiler and the (other) details of the code.

CodePudding user response:

I assume both are still put on the stack so there is no difference?

The only real difference is that if you attempt to modify the variable you'll get a compile time error if it was const (which can be helpful, especially for "maintenance coders", or a future version of you that forgot your original code's details)

If you don't modify it; then a modern compiler will auto-detect that it's not modified and optimize the code without caring if it was/wasn't const (likely including the complete removal of the variable).

  •  Tags:  
  • c
  • Related