Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

like image 729
Amit Singh Tomar Avatar asked Jul 21 '11 10:07

Amit Singh Tomar


People also ask

How many times can a variable be declared in C?

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.

Can we declare variable multiple times?

every time is perfectly fine.

How many times can a variable be declared?

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).


1 Answers

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.

like image 99
pmg Avatar answered Oct 23 '22 11:10

pmg