Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error in c, but not in c++

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??

like image 745
esh Avatar asked Jun 17 '10 11:06

esh


2 Answers

This isn't valid in C89 C, though it may be valid in C99

See this stack overflow question

like image 136
David Sykes Avatar answered Sep 25 '22 13:09

David Sykes


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

like image 24
Johannes Schaub - litb Avatar answered Sep 21 '22 13:09

Johannes Schaub - litb