const int t=5;
char buf[t+5];
When I compile this gives error in C but not in C++!!
Can anybody please explain me the reason?
Note: I know the const defaults to internal linkage in 'C++', where as in 'C' it defaults to external linkage. Does it has any relation to the above case??
This isn't valid in C89 C, though it may be valid in C99
See this stack overflow question
As others explained, C is kept more simple than C++ and doesn't allow const variables to appear in integer constant expressions. But in both C89 and C++ declared arrays must have compile-time constant sizes.
You can use enumerations for this
enum {
BufSize = 5
};
char buf[BufSize + 5];
It doesn't have to do with internal linkage - external linkage variables are equally viable in integer constant expressions in C++. The internal linkage in C++ rather is a consequence, but not a neccessity, of allowing them to appear in constant expressions. The C++ Standard explains why they have internal linkage by default
Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With