Constant Expression Clarification Required

K & R c 2nd edition (section 2.3) mentions

A constant expression is an expression that includes only constants. Such expressions can be evaluated at compile time, rather than at run time, and, accordingly, can be used anywhere where a constant may occur.

however, I have a few doubts about this:

  • Will this expression be considered a constant expression?

    const int x=5;
    const int y=6;
    int z=x+y;
    

    ie is the use of a keyword constconsidered a constant expression or not?

  • Is there any method by which we can check if the expression was evaluated at compile time or at run time?

  • Are there cases where estimating compilation time gives an excellent result than estimating runtime?

  • ? (, )

+4
4
  • . , , , , .
  • () , .
  • , , . : " , " (Β§6.6 11 C11).
  • , .:) const !
+2

const ?

β†’ , . , const, const , .

- , , ?

β†’ ( - Unwind). .

, , ?

β†’ , . . Β§6.6 11, C11.

FWIW, sizeof ( , ), NULL . . NULL undefined .

? (, )

β†’ , .

+1
  • x y - const, z - . , , x y, z. , , compiller 5 + 6 z.

  • , , , .

  • . , .

  • :), , .

0
  • C const - , , . , ++. .

  • gcc builtin (int __builtin_constant_p (exp)), , .

  • , - undefined, -. [1]

  • Because constant expressions are evaluated at compile time, they provide a safe processing time and often use code space and possibly data space. In addition, in some places (for example, global initializers), only constant expressions are allowed. See Standard.


[1]: One example is the right shift of a sign constant with a constant sign, for example. -1 >> 24. Since this implementation is defined, the compiler may give a different result from running the program using a variable that has the same value:

int i = -1;
(-1 >> 24) == (i >> 24)
^             ^--- run-time evaluated by target
+--- compile-time evaluated by compiler

Comparison may fail.

0
source

All Articles