Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of something which is, and is not, a "Constant Expression" in C?

I'm a tad confused between what is and is not a Constant Expression in C, even after much Googleing. Could you provide an example of something which is, and which is not, a Constant Expression in C?

like image 935
Dave Avatar asked Sep 20 '10 21:09

Dave


People also ask

What is not constant in C language?

Moreover, in C language, the term "constant" refers to literal constants (like 1 , 'a' , 0xFF and so on), enum members, and results of such operators as sizeof . Const-qualified objects (of any type) are not constants in C language terminology.

What is example of constant in C?

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.

What is a constant expression in C?

A constant expression gets evaluated at compile time, not run time, and can be used in any place that a constant can be used. The constant expression must evaluate to a constant that is in the range of representable values for that type.

What are the 3 constants used in C?

Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.


2 Answers

A constant expression can be evaluated at compile time. That means it has no variables in it. For example:

5 + 7 / 3

is a constant expression. Something like:

5 + someNumber / 3

is not, assuming someNumber is a variable (ie, not itself a compile-time constant).

like image 117
Carl Norum Avatar answered Sep 22 '22 23:09

Carl Norum


Nobody seems have mentioned yet another kind of constant expression: address constants. The address of an object with static storage duration is an address constant, hence you can do this kind of thing at file scope:

char x;
char *p = &x;

String literals define arrays with static storage duration, so this rule is also why you can do this at file scope:

char *s = "foobar";
like image 43
caf Avatar answered Sep 23 '22 23:09

caf