Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer element is not constant in C [duplicate]

Tags:

I'm coming from javascript/php/python and probably I'm missing something, here is the code:

const int a = 50;
const int c = 100;
const int d = 100;
int endX = c + a;
int endY = d;
int startX, startY, b;

I get

ex1.4.c:6: error: initializer element is not constant
ex1.4.c:7: error: initializer element is not constant

Does someone have an explanation?

like image 257
piggyback Avatar asked Oct 05 '12 16:10

piggyback


People also ask

What does initializer element is not constant mean?

It's not inside a function, which means it has to be an initializer - which is assigned only when the item is declared - which means it must be a constant value at compile time, which malloc cannot be.

Which is not constant in C?

Const-qualified objects (of any type) are not constants in C language terminology. They cannot be used in initializers of objects with static storage duration, regardless of their type.


2 Answers

Unfortunately, in C const variables are not really const.

Below are the extracts from the c99 standard.

6.7.8 Initialization

  1. All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

The constants are defined as follows:

6.4.4 Constants

Syntax

constant:

integer-constant       (e.g. 4, 42L)
floating-constant      (e.g. 0.345, .7)
enumeration-constant   (stuff in enums)
character-constant     (e.g. 'c', '\0')

The standard defines constant expressions as follows:

6.6 Constant expressions

(7) More latitude is permitted for constant expressions in initializers. Such a constant expression shall be, or evaluate to, one of the following:

— an arithmetic constant expression,

— a null pointer constant,

— an address constant, or

— an address constant for an object type plus or minus an integer constant expression.

(8) An arithmetic constant expression shall have an arithmetic type and shall only have operands that are integer constants, floating constants, enumeration constants, character constants, and sizeof expressions. Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types, except as part of an operand to a sizeof operator whose result is an integer constant.

Thus, c and a are not constant expressions and cannot be used as initializers in your case.

like image 142
Maksim Skurydzin Avatar answered Oct 28 '22 23:10

Maksim Skurydzin


const expressions must be a compile time constant in C unlike in C++ therefore c+a can't be used as a constant. The usual way to handle this problem in C is to use the preprocessor instead:

#define A 50
#define C 100
#define D 100
int endX = C + A;
int endY = D;
int startX, startY, b;
like image 23
none Avatar answered Oct 29 '22 01:10

none