Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Legal and illegal declaration and initializations in C
In C programming, variable declaration and initialization must follow specific rules. Understanding legal and illegal practices helps write error-free code and avoid compilation issues.
Syntax
// Variable Declaration datatype variable1, variable2, ..., variableN; // Variable Initialization datatype variable = value;
Variable Declaration
Variables can be declared in two scopes −
- Global declaration: Variables declared outside any function, accessible throughout the program.
- Local declaration: Variables declared inside a function, accessible only within that function.
#include <stdio.h>
int globalVar; /* global declaration */
int main() {
int localVar; /* local declaration */
globalVar = 100;
localVar = 50;
printf("Global: %d, Local: %d<br>", globalVar, localVar);
return 0;
}
Global: 100, Local: 50
Legal and Illegal Declarations
Legal Examples
-
char a = 65;− Legal because we can initialize with a constant value. -
double x = 30 * 3.14;− Legal because we initialize with a constant expression. -
int arr[] = {1, 2, 3, 4};− Legal array initialization with constants.
#include <stdio.h>
int main() {
char a = 65;
double x = 30 * 3.14;
int arr[] = {1, 2, 3, 4};
printf("a = %c (ASCII: %d)<br>", a, a);
printf("x = %.2f<br>", x);
printf("arr[0] = %d, arr[1] = %d<br>", arr[0], arr[1]);
return 0;
}
a = A (ASCII: 65) x = 94.20 arr[0] = 1, arr[1] = 2
Illegal Examples
-
static int p = 20, q = p * p;− Illegal because static variables must be initialized with constants, not other variables. -
int size; int arr[size];− Illegal in C89/C90 (legal in C99+ with VLA support).
#include <stdio.h>
int main() {
static int p = 20, q = p * p; /* This will cause compilation error */
printf("%d %d<br>", p, q);
return 0;
}
error: initializer element is not constant
static int p = 20, q = p * p;
Key Points
- Static and global variables must be initialized with compile-time constants.
- Local variables can be initialized with any valid expression.
- Array size must be a constant expression in C89/C90.
- Variables should be declared before use in their respective scope.
Conclusion
Following proper declaration and initialization rules prevents compilation errors. Static variables require constant initializers, while local variables offer more flexibility in initialization expressions.
Advertisements
