We are transitioning C code into C++.
I noticed that the following code is well defined in C,
int main(){
//length is valid. '\0' is ignored
char str[3]="abc";
}
as it is stated in Array initialization that:
"If the size of the array is known, it may be one less than the size of the string literal, in which case the terminating null character is ignored."
However, if I were to build the same code in C++, I get the following C++ error:
error: initializer-string for array of chars is too long
[-fpermissive] char str[3]="abc";
I'm hoping someone can expound on this.
Questions:
Is the code example valid in all C language standards?
Is it invalid in all C++ language standards?
Is there a reason that is valid in one language but not another?
char*
conversions (though that took a while), this, andvoid*
toT*
conversions. – Punyinline
, flexible array members vs. zero-length arrays). And many features never made it into the standard. – Osteoplastic"\&"
if they did not use backslash-ampersand as an escape for any other purpose (or substitute any other character they don't use as an escape); alternatively, C compilers could simply define the macro as nothing at the cost of needlessly wasting an extra byte in contexts where the string yields a pointer, or possible compiler squawks if used for array initialization. – Crispationconst
qualifier has different semantics, VLAs do not exist in C++ neither do FAMs. And apparently such things like the above are also not compatible. Re the libraries: That would make Go or Python also C compatible, because they can use the same libraries. Sorry, but that is nonsense! – Osteoplasticchar str[] = { 'a', 'b', 'c' }; // look ma, no NUL
– Dozierconst
is a feature "back-ported" from C++? This seems to support rather than disprove that the committees try to preserve compatibility where possible and adequate. With respect to the origin of some of the (slightly) differentconst
semantics you may be interested in James Kanze's illuminating post at https://mcmap.net/q/272974/-what-is-the-difference-in-const-correctness-between-c-and-c. With respect to header and library use: I don't think you can#include stdio.h
in Python. That go, otoh, can use them with cgo is also by design and thus rather an argument for C++'s compatibility. – Indiscreteconst int i = 10;
static int a[i];! Funny enough, while I cannot
#include` the header directly, it is no problem to call the functions from Python viactypes
. More direct for other languages. A header is not necessary to use a C function anyway, you can provide your own declarations. So what does that prove? Interestingly, you silently ignore VLAs and FAMs, introduced along withconst
C99. – Osteoplastic