4 ms·
The code: const size_t buffer_size = 5; int buffer[buffer_size]; compiles fine in c, but not for the same reason. C99/C11 has dynamic arrays https://en.wikip
by powzapbiff 7y ago
The code:
const size_t buffer_size = 5;
int buffer[buffer_size];
compiles fine in c, but not for the same reason.
C99/C11 has dynamic arrays
https://en.wikipedia.org/wiki/Variable-length_array#C99 https://en.wikipedia.org/wiki/Variable-length_array#C99
- lochsh 7y agoYes, I think I made an embarrassing mess up here by using a compiler that doesn't support VLAs, and not fully understanding VLAs. Thanks for pointing it out.
- eMSF 7y agoTo be exact, it doesn't compile fine outside of functions (which the sample code didn't have) because file scope arrays can't be VLAs.
- lochsh 7y agoThis is what I was going for in the blog post, but I got confused after seeing these comments as Clang _does_ compile this when the buffer is of static storage class. Which I don't think is standard -- but it's not using VLAs. I wondered if it just has constant expression semantics for const variables. Weirdly, adding a _Static_assert to test this theory proves it for c99 but not c11 :/ https://godbolt.org/z/q-bb-n https://godbolt.org/z/q-bb-n c99 with clang https://godbolt.org/z/ad14Ah https://godbolt.org/z/ad14Ah c11 with clang https://godbolt.org/z/xJSDQa https://godbolt.org/z/xJSDQa c11 with gcc (which is the only one giving the output I'd expect)
- eMSF 7y ago>I wondered if it just has constant expression semantics for const variables. That would be my guess also, for applicable const variables. File scope const variables are quite constexpr-y in C anyway, since C requires all file scope variable initializers to be constant expressions (C++ only requires that for constexpr variables). Toying around with clang in Godbolt, it seems that there are some quirks regarding this. The following is accepted: static const int n = 0; int buf[n]; // invalid zero-length array is accepted // probably another non-standard extension But the following is not, despite n having the same zero value: static const int n; int buf[n]; // complains about a file scope VLA
- _kst_ 7y agoThe C standard permits implementations to support additional forms of constant expressions. Try "clang -std=c11 -pedantic-errors".