0

What I'm asking is does a C const variable defined in such a way that its value is known at compile time:

const int num = 3;
int main(){
    int arr[num];
}

act in the same way as a preprocessor define:

#define num 3
int main(){
    int arr[num];
}

In that the compiled code would look like:

int main(){
    int arr[3];
}

In both cases?

Now there might be a nuance where the code with the const looks more like:

const int num = 3;
int main(){
    int arr[3];
}

Which would also be acceptable, but you understand what I'm asking, which is whether it needs to reference the const at runtime.

Ethan
  • 161
  • 2
  • 19
  • 2
    TLDR: `const int num = 3;` is not an [integer constant expression](https://port70.net/~nsz/c/c11/n1570.html#6.6p6) and thus can not be used to declare arrays other than VLAs (which Microsoft never implemented and managed to cajole the C11 committee into making optional) – Andrew Henle Jun 03 '23 at 19:05
  • No, but C23 will bring a limited version of `constexpr` to C which will muddy the waters a bit more. – David C. Rankin Jun 03 '23 at 23:03
  • @Ethan, Try coding `const int num1 = 3; const int *ptr1 = &num1;` and `#define num2 3 int *ptr2 = &num2;`. `const int num1` does not always work like `#define num2`. – chux - Reinstate Monica Jun 04 '23 at 00:55

1 Answers1

1

You can use https://godbolt.org/ to see this - even with -O0, the compiler seems to define the constant:

a:
        .long   3

But then reference it as a literal during calls, like a macro, for both array length and printf calls which I tested with:

        mov     eax, 3

See example here - a is 9999 to make it more obvious in the assembly https://godbolt.org/z/o6qvaTrY4

However, when using constant pointers, as in this example: https://godbolt.org/z/x59csqMYE at -O0, the compiler starts to reference the constant instead of just using its literal value. At -O3 though, it goes back to inserting the literal straight into the assembly.

CoderMuffin
  • 519
  • 1
  • 10
  • 21
  • 1
    That's ignoring the most important difference on the language level: `num` is not an integer constant expression with `const int num = 3;` and therefore will cause `arr` to be a VLA (if at all). – user17732522 Jun 03 '23 at 19:37