I have the below C code and I am expecting 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
Though we can declare one variable various times in a C program, we can only define it once in a function, a file, or any block of code.
every time is perfectly fine.
A variable or function can be declared any number of times, but it can be defined only once. (Remember the basic principle that you can't have two locations of the same variable or function).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With