Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "const extern" give an error?

The following piece of code working fine:

#include <stdio.h>

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

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

But, the following piece of code give an error:

#include <stdio.h>

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

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

So, why does const extern give an error?

like image 286
msc Avatar asked Jul 06 '17 06:07

msc


3 Answers

Standard says:
C11-§6.7/4

All declarations in the same scope that refer to the same object or function shall specify compatible types

const int and int are not compatible for the same object foo in the same scope.

like image 80
haccks Avatar answered Nov 19 '22 15:11

haccks


These two declarations are contradictory:

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

The first one declares foo as const, and the second one declares it as non const.

Error messages:

prog.cpp:4:5: error: conflicting declaration
   ‘int foo’ int foo = 42; 
         ^~~
 prog.cpp:3:18: note: previous declaration as ‘const int foo’
    const extern int foo; // With constant 
                     ^~~
like image 20
Jabberwocky Avatar answered Nov 19 '22 16:11

Jabberwocky


You say foo is const and then try to change its constness with the other declaration. Do this and you should be fine.

  const extern int foo; // With constant
  const int foo = 42;
like image 3
Gaurav Sehgal Avatar answered Nov 19 '22 15:11

Gaurav Sehgal