Why does const extern give an error?

The following code snippet works fine:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

But the following code gives an error:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

So why const externgives an error?

+4
source share
3 answers

The standard says:
C11-§6.7 / 4

All declarations in the same scope that relate to the same object or function must indicate compatible types.

const intand intnot compatible for the same object fooin the same area.

+6
source

These two declarations are contradictory:

const extern int foo; // With constant
int foo = 42;

The first declares it fooas const, and the second declares it as not const.

Error messages:

prog.cpp:4:5: error: conflicting declarationint foo’ int foo = 42; 
         ^~~
 prog.cpp:3:18: note: previous declaration asconst int foo’
    const extern int foo; // With constant 
                     ^~~
+4

You say foois const, and then try changing its constant with a different declaration. Do it and everything will be fine.

  const extern int foo; // With constant
  const int foo = 42;
+3
source

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


All Articles