Not a permanent element of initialization?

I came across a confusing case when I was doing semantic analysis for my compiler course.

#include <stdio.h>

int a = "abcd"[2];

int main()
{
    char b = "abcd"[2];

    printf("%d\n%c\n", a, b);

    return 0;
}

GCC says: "error: the initializer element is not a constant" for the variable "a".

Why?

+6
source share
2 answers

The C language requires that initializers for global variables be constant expressions. The motivation is for the compiler to evaluate the expression at compile time and write the calculated value to the generated object file.

Standard C provides specific rules for what is a constant expression:

  1. 117) , , , sizeof, , _Alignof , . Cast , sizeof _Alignof.
  2. . , , :
    • ,
    • ,
    • .

, . , "abcd"[2] .

:

  1. .

, , "abcd"[1] , .

, . , ( , isConstantExpression, , ).

+5

int a = "abcd" [2];

a - initilize , "abcd" [2] .

char b = "abcd" [2];

b "abcd" [2].

0

Source: https://habr.com/ru/post/1016116/


All Articles