Skip to content

Compile time constant

Johnson Tan edited this page Mar 7, 2016 · 4 revisions

Integral constants

integral constant
  : int-const
  | enum-const
  | char-const
  | (integral-type) arith-const
  | sizeof expr

Example

// global
int a;
long b = (long)&a;

gcc: b: .long a

clang: error: initializer element is not a compile-time constant

Example

// global
struct some_struct {
    int a;
    int b;
} inst1, inst2;
int a = &inst1.a - &inst1.b; // Requires compile-time address calculation.

gcc: okay

clang: okay

Arithmetic constants

arith-const
  : int-const
  | float-const
  | enum-const
  | char-const
  | sizeof expr
  | (arith-type) arith-const

Example

// global
int a = 3;
int b = a;

gcc: error: initializer element is not constant

clang: error: initializer element is not a compile-time constant

Address constants

An address constant is a pointer to an lvalue designating an object of static storage duration, or to a function designator; it shall be created explicitly, using the unary & operator, or implicitly, by the use of an expression of array or function type. The array-subscript [] and member-access . and -> operators, the address & and indirection * unary operators, and pointer casts may be used in the creation an address constant, but the value of an object shall not be accessed by use of these operators.

addr-const
  : &(static-lvalue)
  | func-designator
  | 

Example

// global
int a[10];
int *b = &a[1];

gcc: b: .long a+4

clang: b: .long a+4

Clone this wiki locally