Predict the output of following C programs.
Both of the above programs don’t compile in C. We get the following compiler error in C.
error: initializer element is not constant
In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value.
Note that the above programs compile and run fine in C++, and produce the output as 10.
As an exercise, predict the output of following program in both C and C++.
This article is contributed by Shankar Shastri. 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.
- Initialization of static variables in C
- Difference between Static variables and Register variables in C
- Initialization of variables sized arrays in C
- Implicit initialization of variables with 0 or 1 in C
- Can Global Variables be dangerous ?
- Internal static variable vs. External static variable with Examples in C
- How are variables scoped in C - Static or Dynamic?
- What are the default values of static variables in C?
- Static Variables in C
- Initialization of data members
- Initialization of a multidimensional arrays in C/C++
- How Linkers Resolve Global Symbols Defined at Multiple Places?
- Can we access global variable if there is a local variable with same name?
- Redeclaration of global variable in C
- Difference between Static and Shared libraries
- Difference between Static and Dynamic Memory Allocation in C
- Static functions in C
- Can static functions be virtual in C++?
- Static data members in C++
- When are static objects destroyed?