Constant Expression in C


A constant expression is an expression that the compiler can reduce to a known value before it reads any more of the source file.

In some contexts, the C language requires expressions that evaluate to a constant. These contexts are as follows:

  • When a case constant is evaluated in switch statements

  • When the size of an array is evaluated

  • When initializers are evaluated

  • When specifying the size of a bit field member of a structure

  • When the value of an enumeration constant is evaluated

  • When the tested value in the #if preprocessor statement is evaluated

The C compiler imposes slightly different restrictions on the form of expression it allows in each context.

If the expression is evaluated by the compiler, the arithmetic precision and range are at least as great as if the expression were being evaluated in the execution environment.

A constant expression can do the following:

  • Contain integer expressions

  • Use casts to integral types (Casts are not allowed in #if type expressions.)

  • Use the following binary operators:

    *   /    %     +     -    <<   >>  ==   !=
    <   <=   >     >=    &    ^    |   &&   || 
  • Use the following unary operators:

    +   -   ~   !
  • Use the following conditional operator:

    ?:
  • Use parentheses for grouping

A function call operator, an increment and decrement operator, and an assignment operator are not allowed in constant expressions.

An integral constant expression must involve only integer, enumeration, or character constants, and casts to integral types. The following operators must not appear in an integral constant expression, unless the expression is the operand of the sizeof operator:

  • Array subscripting operator ([ ])

  • Direct member selection operator (.)

  • Indirect member selection operator (->)

  • Address operator (&)

  • Indirection operator (*)

For constant expressions in initializers, floating-point constants and arbitrary casts can be used in addition to integral constant expressions. Lvalues and objects that have static storage duration or function identifiers can also be used to specify addresses, explicitly with the unary & operator or implicitly for unsubscripted array identifiers or function identifiers. A constant difference in the addresses of two members of the same aggregate can be used.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.