
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Initialization of global and static variables in C
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
A program that demonstrates the initialization of global and static variables is given as follows.
Example
#include <stdio.h> int a = 5; static int b = 10; int main() { printf("The value of global variable a : %d", a); printf("
The value of global static variable b : %d", b); return 0; }
Output
The output of the above program is as follows.
The value of global variable a : 5 The value of global static variable b : 10
Now, let us understand the above program.
The global variable a has the value 5 and the static variable b has the value 10. So, this program works as required.
If constants are not used to initialize the global and static variables, this will lead to an error. A program that demonstrates this is as follows.
#include <stdio.h> int func() { return 25; } int main() { static int a = func(); printf("%d ", a); }
The above program leads to a error “initializer element is not constant”. So, global and static variables should only be initialized with constants.
- Related Articles
- Initialization of static variables in C
- C++ static member variables and their initialization
- Why are global and static variables initialized to their default values in C/C++?
- Static Data Member Initialization in C++
- Global and Local Variables in C#
- What are local variables and global variables in C++?
- Class and Static Variables in C#
- Templates and Static variables in C++
- Static Variables in C
- Implicit initialization of variables with 0 or 1 in C
- What are global variables in C++?
- A static initialization block in Java
- Default values of static variables in C
- Difference between static, auto, global and local variable in C++
- Why are global variables bad in C/C++?
