开发者

In C, is it valid to declare a variable multiple times?

I have the below C code and I am expecti开发者_StackOverflowng it to throw an error like "multiple declaration of variable", but it is not doing so.

#include <stdio.h>

int i;        
int i;    

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

Now the output is 0, but why?

And one more thing below code gives error what is expected

#include <stdio.h>


int main()
{
    int i;        
    int i;    

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

O/p is error saying re declaration of i


The first definition of i is a tentative definition (the 2nd is also a tentative definition). They are "de facto" definitions though (and definitions serve also as declarations), no mistake about it.

Quote from the Standard:

6.9.2/2

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜