Initialization of global and static variables in C Last Updated : 08 May, 2017 Comments Improve Suggest changes Like Article Like Report Predict the output of following C programs. C // PROGRAM 1 #include <stdio.h> #include <stdlib.h> int main(void) { static int *p = (int*)malloc(sizeof(p)); *p = 10; printf("%d", *p); } C // PROGRAM 2 #include <stdio.h> #include <stdlib.h> int *p = (int*)malloc(sizeof(p)); int main(void) { *p = 10; printf("%d", *p); } 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++. C #include <stdio.h> int fun(int x) { return (x+5); } int y = fun(20); int main() { printf("%d ", y); } Comment More infoAdvertise with us Next Article Initialization of global and static variables in C K kartik Improve Article Tags : C Language C Basics Similar Reads Initialization of Static Variables in C In C, a static variable are those variables whose lifetime is till the end of the program. It means that once it is initialized, it will live in the program till it ends. It can retain its value between function calls, unlike regular local variables that are reinitialized each time the function is c 2 min read Implicit initialization of variables with 0 or 1 in C In C programming language, the variables should be declared before a value is assigned to it. For Example: // declaration of variable a and // initializing it with 0. int a = 0; // declaring array arr and initializing // all the values of arr as 0. int arr[5] = {0}; However, variables can be assigne 2 min read Redeclaration of global variable in C Consider the below two programs: C // Program 1 int main() { int x; int x = 5; printf("%d", x); return 0; } Output in C: redeclaration of âxâ with no linkage C // Program 2 int x; int x = 5; int main() { printf("%d", x); return 0; } Output in C: 5 In C, the first program fails in 1 min read How are variables scoped in C - Static or Dynamic? In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() 1 min read Global Variables in C Prerequisite: Variables in C In a programming language, each variable has a particular scope attached to them. The scope is either local or global. This article will go through global variables, their advantages, and their properties. The Declaration of a global variable is very similar to that of a 3 min read Like