I'm following an exercise in which I have to prove the difference between C and C++ constant expressions. It is valid to write something like this in C++:
const int size_1 = 2;
const int size_2 = 2;
const int arr[size_1 + size_2] = { 1, 2, 3, 4 };
int main() {
return arr[0];
}
but I would expect that it would throw an error when copied to .c file and compiled in C - in fact I've used online compiler to check it and it returned:
main.c:6:11: error: variably modified ‘arr’ at file scope
which I believe is what I'm looking for.
But when I compile exactly the same code with a command gcc main.c
on my machine, the code compiles without an error and returned value is correct. Could someone explain where is my mistake?
My compiler version:
Apple clang version 15.0.0 (clang-1500.0.40.1)
Target: arm64-apple-darwin23.0.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
(a) The C standard does not require compilers to issue diagnostic messages or to reject programs using forms of constants not defined by the C standard (or to reject programs with undefined behavior generally). The standard requires programs to issue a diagnostic message for violations of syntax rules and rules explicitly listed as constraints (per C 2018 5.1.1.3 1), but using
const
variables in an expression for array size is not such a violation. For other violations of “requirements” in the standard, the standard does not define what must happen (C 2018 4 2), and an implementation may accept such programs (C 2018 4 6).(b) The C standard explicitly allows implementations to accept other forms of constant expressions (C 2018 6.6 10, “An implementation may accept other forms of constant expressions”).
(c) Testing with Clang 15.0.0 for ARMv8 on Compiler Explorer produces the message “variable length array folded to constant array as an extension [-Wgnu-folding-constant]” even with default compiler options. I do not have the Apple version of Clang 15.0.0 to test, so, if you do not see that message, this seems to be a difference in the Apple version. Adding the switches
-std=c18 -pedantic-errors
will likely cause the compiler to reject this code.