Related Articles

Related Articles

Initialization of global and static variables in C
  • Difficulty Level : Medium
  • Last Updated : 08 May, 2017

Predict the output of following C programs.

filter_none

edit
close

play_arrow

link
brightness_4
code

// PROGRAM 1
#include <stdio.h>
#include <stdlib.h>
  
int main(void)
{
   static int *p = (int*)malloc(sizeof(p));
   *p = 10;
   printf("%d", *p);
}

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

// PROGRAM 2
#include <stdio.h>
#include <stdlib.h>
int *p = (int*)malloc(sizeof(p));
  
int main(void)
{
    *p = 10;
    printf("%d", *p);
}

chevron_right


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++.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
int fun(int x)
{
    return (x+5);
}
  
int y = fun(20);
  
int main()
{
    printf("%d ", y);
}

chevron_right


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 C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :