38

I cannot understand why doing this is wrong:

const int n = 5; 
int x[n] = { 1,1,3,4,5 };

even though n is already a const value.

While doing this seems to be right for the GNU compiler:

const int n = 5;
int x[n]; /*without initialization*/

I'm aware of VLA feature of C99 and I think it's related to what's going on but I just need some clarification of what's happening in the background.

15
  • I suspect if you tack static on the definition of n, it will work; static const would be true global compile time constant, not stack stored constant. Commented Feb 2, 2016 at 19:24
  • 10
    @ShadowRanger: C is not C++. The semantics of const is one of the differences. C does not have symbolic constant. E.g. 1 is an integer constant as of the C standard. const int i is still a variable! Commented Feb 2, 2016 at 19:31
  • 3
    const is just a promise you give to the compiler you will not change a variable, neither directly, nor indirectly. For the first most compilers will warn, for the latter (e.g. through pointers) they are very limited in detecting all possible violations. If you violate the contract you invoke undefined behaviour. Commented Feb 2, 2016 at 19:33
  • 2
    @Olaf, C has some symbolic constants where you perhaps wouldn't expect them, namely enumerations. Commented Feb 2, 2016 at 20:27
  • @JensGustedt: Yeah, I always forget about those. They are some special kind, mostly because you cannot explicitly specify their type (something C11 should also have copied from C++11 making enums finally useful). And the two "boolean" constants _True and _False which are not user-definable. Hmm, as you wrote "namely" which implies there are others, too: any other user-definable symbolic constants I forgot about? (serious question, I might have overlooked something simple - if you're in the woods, you only see trees) Commented Feb 2, 2016 at 20:54

5 Answers 5

36

The key thing to remember is that const and "constant" mean two quite different things.

The const keyword really means "read-only". A constant is a numeric literal, such as 42 or 1.5 (or an enumeration or character constant). A constant expression is a particular kind of expression that can be evaluated at compile time, such as 2 + 2.

So given a declaration:

const int n = 5;

the expression n refers to the value of the object, and it's not treated as a constant expression. A typical compiler will optimize a reference to n, replacing it by the same code it would use for a literal 5, but that's not required -- and the rules for whether an expression is constant are determined by the language, not by the cleverness of the current compiler.

An example of the difference between const (read-only) and constant (evaluated at compile time) is:

const size_t now = time(NULL);

The const keyword means you're not allowed to modify the value of now after its initialization, but the value of time(NULL) clearly cannot be computed until run time.

So this:

const int n = 5;
int x[n];

is no more valid in C than it would be without the const keyword.

The language could (and IMHO probably should) evaluate n as a constant expression; it just isn't defined that way. (C++ does have such a rule; see the C++ standard or a decent reference for the gory details.)

If you want a named constant with the value 5, the most common way is to define a macro:

#define N 5
int x[N];

Another approach is to define an enumeration constant:

enum { n = 5 };
int x[n];

Enumeration constants are constant expressions, and are always of type int (which means this method won't work for types other than int). And it's arguably an abuse of the enum mechanism.

Starting with the 1999 standard, an array can be defined with a non-constant size; this is a VLA, or variable-length array. Such arrays are permitted only at block scope, and may not have initializers (since the compiler is unable to check that the initializer has the correct number of elements).

But given your original code:

const int n = 5; 
int x[n] = { 1,1,3,4,5 };

you can let the compiler infer the length from the initializer:

int x[] = { 1,1,3,4,5 };

And you can then compute the length from the array's size:

const int x_len = sizeof x / sizeof x[0];
Sign up to request clarification or add additional context in comments.

4 Comments

"A constant is a numeric literal". Is this strictly true? There must be some other types of constants?
OT, but: "C++ does have such a rule [to evaluate n as a constant expression]". Well, only sometimes; to make this phrase really accurate, you'd need to substitute constexpr. Using just const might work in some cases, but it does not guarantee a "constant expression" in C++, depending on context. e.g.: stackoverflow.com/questions/18996258/…
@artm: You're right, there are 4 kinds of constants in C: integer, floating, enumeration, and character.
@underscore_d: Yes, the C++ rule is a bit more complicated -- but it does apply in this particular case. I've added some weasel words.
21

Why int x[n] is wrong where n is a const value?

n is not a constant. const only promise that n is a 'read-only' variable that shouldn't be modified during the program execution.
Note that in , unlike , const qualified variables are not constant. Therefore, the array declared is a variable length array.
You can't use initializer list to initialize variable length arrays.

C11-§6.7.9/3:

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

You can use #define or enum to make n a constant

#define n 5
int x[n] = { 1,1,3,4,5 };   

13 Comments

@Yahia Farghaly n is a variable, it is const, but not constant. const effectively means read-only in C.
@chux: Actually, it is not guaranteed to be read-only. It is just a guarantee by the programmer to the compiler. The compiler will not be able to detect all violations, nor is the run-time environment required to.
@Oalf - True, It was an mis-guided over-oversimplification for the OP.
note: in C++, const-qualified variables may or may not be constant expressions, e.g. const int n = rand() % 5; int x[n]; is correct in C but not C++ !
@artm; You can use #define or enum.
|
7

If you are exhaustively initialising an array, then it is easier, safer and more maintainable to let the compiler infer the array size:

int x[] = { 1,1,3,4,5 };
const int n = sizeof(x) / sizeof(*x) ; 

Then to change the array size you only have to change the number of initialisers, rather than change the size and the initialiser list to match. Especially useful when there are many initialisers.

Comments

3

Even though n is a const, you cannot use it to define the size of an array unless you wish to create a VLA. However, you cannot use an initializer list to initialize a VLA.

Use a macro to create a fixed size array.

#define ARRAY_SIZE 5

int x[ARRAY_SIZE] = { 1,1,3,4,5 };

5 Comments

@chux: You cannot have a static VLA.
An enumerated constant would do too if you want to keep the constant within a block or function scope: enum { n = 5 }; int x[n] = { 1,1,3,4,6 };
Hmm, this cannot be a serious advice; one does not pollute the global space of symbols, implying potential and very hard to find bugs, just to create a fixed size array.
Ugh. Not bothering to change the name makes this terrible advice. Everyone, please do not name any macro like this, ever. Just imagine the horror that can result from hijacking any common name, especially a single letter, and especially the exceedingly generic n. Macros (or at least 99.9% of them) should have HUGE_SHOUTY_AND_UGLY_NAMES, precisely to make them difficult and unappealing to (ab)use.
@underscore_d,use of n was for illustration purposes only but point well made.
2

Is your code semantically different from myfunc() here:

void myfunc(const int n) { 
    int x[n] = { 1,1,3,4,5 };
    printf("%d\n", x[n-1]);
    *( (int *) &n) = 17;    //  Somewhat less "constant" than hoped...
    return ;
}

int main(){
    myfunc(4);
    myfunc(5);
    myfunc(6);  //  Haven't actually tested this.  Boom?  Maybe just printf(noise)?
    return 0;
}

Is n really all that constant? How much space do you think the compiler should allocated for x[] (since it is the compiler's job to do so)?

As others have pointed out, the cv-qualifier const does not mean "a value that is constant during compilation and for all times after". It means "a value that the local code is not supposed to change (although it can)".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.