Why is there such a difference in global variable initialization between C and C ++?

Take a look at these programs:

#include<stdio.h>

int i;       //C implementation works fine with this initialization of variable i
i=108;

int main()
{
    printf("%d",i);
    return 0;
}

      

In this code (C ++ version) it throws an error:

'i does not name type I = 99;

#include<iostream>

using namespace std;

int i;
i=99;

int main()
{
    cout<<i<<endl;
    return 0;
}

      

Now I read that the reason for the successful launch of the C version is an implicit int that was later removed from the C99 version.

1: Is this preventing the C ++ version from working successfully ?

2: If this implicit int is the cause of the 1st code, then why doesn't the compiler throw an "i" error that is defined twice?

Please indicate my misunderstanding of the concept.

+3


source to share


2 answers


In C it's in the global scope

int i;
i = 42;

      

takes the second line as a redefinition of what was defined in the 1st. If the types match the compiler, it takes it and concatenates the "two i

s" into one.

In the above example, types match, due to the implicit application of the "do something unknown rule int

" rule , to the second definition i

.

The following lines, for example, will not compile:



float f;
f = 42;

      

since the 2nd f

would be accepted as int

which does not match the type of the 1st f

, which is float

.


Not 100% sure about C ++, but I'm guessing this "do something unknown int

" rule just doesn't exist in C ++. So globally something seems to be i = 42;

invalid, which is completely independent of whether it was declared or defined i

before or after.

+4


source


At this point in the file, any line of code must be a declaration; it cannot be the destination of an existing object.

There is a rule in C that a declaration can leave a type (it will default int

), so your string can be parsed as a declaration (and definition with an initializer) in that language. Also, since C has preliminary definitions , this "second" definition is allowed:



int i;        // tentative definition
int i = 42;   // "int" added automatically

      

These two rules combine to make the code valid in C. C ++ has neither of them. So in C ++ is i = 42

not a declaration and your code is not valid. Period.

+3


source







All Articles