Consider the below two programs:
// Program 1 int main() { int x; int x = 5; printf("%d", x); return 0; } |
chevron_right
filter_none
Output in C:
redeclaration of ‘x’ with no linkage
// Program 2 int x; int x = 5; int main() { printf("%d", x); return 0; } |
chevron_right
filter_none
Output in C:
5
In C, the first program fails in compilation, but second program works fine. In C++, both programs fail in compilation.
C allows a global variable to be declared again when first declaration doesn’t initialize the variable.
The below program fails in both C also as the global variable is initialized in first declaration itself.
int x = 5; int x = 10; int main() { printf("%d", x); return 0; } |
chevron_right
filter_none
Output:
error: redefinition of ‘x’
This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Can we access global variable if there is a local variable with same name?
- Internal static variable vs. External static variable with Examples in C
- Can Global Variables be dangerous ?
- Initialization of global and static variables in C
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- How to print a variable name in C?
- Variable Length Arrays in C and C++
- Different ways to initialize a variable in C/C++
- How to modify a const variable in C?
- Variable Length Argument in C
- Why variable name does not start with numbers in C ?
- C | Variable Declaration and Scope | Question 5
- Different ways to declare variable as constant in C and C++
- C | Variable Declaration and Scope | Question 6
- C | Variable Declaration and Scope | Question 7
- C | Variable Declaration and Scope | Question 8
- Variable length arguments for Macros
- C | Variable Declaration and Scope | Question 2
- C | Variable Declaration and Scope | Question 1
- C | Variable Declaration and Scope | Question 3

