Why is const a + const b not a constant itself?

I am making a clone clone for testing the SDK ... For several years I have not been C.

Anyway, I tried to do this at the const setup step:

const int SCREEN_W = 480;
const int SCREEN_H = 480;
const int PLAYER_H_WIDTH = 50;
const int PLAYER_H_HEIGHT = 12;
const int BUFFER = 14;
const int LEFT_BUFFER = PLAYER_H_WIDTH+BUFFER;
const int RIGHT_BUFFER = SCREEN_W-LEFT_BUFFER;

except that the compiler throws an error in the lines LEFT_BUFFERand RIGHT_BUFFERthat makes me wonder why?

If the answer is “because the standard says so,” I still want to know why (why does the standard say so?)

EDIT due to comments:

haccks noticed that these lines inside the function (for example, main () {}) are compiled, but not in the file area. I also ask why?

Also a specific GCC error (actually MingW): initializer element is not constant

+4
source share
4 answers

, ( static), .

:

const int PLAYER_H_WIDTH = 50;

PLAYER_H_WIDTH . const "" (.. ); " ".

, :

const int LEFT_BUFFER = PLAYER_H_WIDTH+BUFFER;

LEFT_BUFFER .

: ISO C, 2011 , 6.7.9, 4:

, .

const constant, :

const int r = rand();

- , . ( "" ) r (.. ), (.. ).

- C, main.

++ , ; C . ++ ; , , . , C ++; , , (, ).

:

#define PLAYER_H_WIDTH 50
/* ... */
#define LEFT_BUFFER (PLAYER_H_WIDTH+BUFFER)

enum:

enum { PLAYER_H_WIDTH = 50 };
enum { LEFT_BUFFER = PLAYER_H_WIDTH+BUFFER };

int. , enum , - int.

+6

, . a + b a - b. ,

const int LEFT_BUFFER = BUFFER;

+ -.

, , , . , SCREEN_W .

C "" (, 42) . , const, "" C. " ", , , .

, C. , C. C, #define enum. const. const ( #define), , const C, const .

. C. PLAYER_H_WIDTH, BUFFER .. , . + -,

const int LEFT_BUFFER = BUFFER;

.

, . . , - . , static , .

+1

C "", . , . .

C #define, .

 enum {
    SCREEN_W = 480,
    SCREEN_H = 480,
    PLAYER_H_WIDTH = 50,
    PLAYER_H_HEIGHT = 12,
    BUFFER = 14,
    LEFT_BUFFER = PLAYER_H_WIDTH+BUFFER,
    RIGHT_BUFFER = SCREEN_W-LEFT_BUFFER
 };

, .

0

#define, !

const int SCREEN_W = 480;
const int SCREEN_H = 480;
const int PLAYER_H_WIDTH = 50;
const int PLAYER_H_HEIGHT = 12;
const int BUFFER = 14;
#define  LEFT_BUFFER  PLAYER_H_WIDTH + BUFFER
#define  RIGHT_BUFFER  SCREEN_W - LEFT_BUFFER

#define - ; , . .

, , . : , , , .

const , .

0

All Articles