2 votes 2 votes What is the output of the below mentioned code snippet? #include <stdio.h> int main() { int i=10; static int x=i; if(x==i) printf("Equal"); else if(x>i) printf("Greater"); else printf("Lesser"); return 0; } Equal Greater Lesser Compilation Error Programming in C tbb-programming-2 + – Bikram asked May 14, 2017 edited Aug 19, 2019 by Counsellor Bikram 693 views answer comment Share Follow See all 13 Comments See all 13 13 Comments reply Show 10 previous comments Bikram commented Jul 31, 2017 reply Follow Share @ SKP Yes, because you use const int i=10; if there is no constant then error is given. Because all objects with static storage duration must be initialized (set to their initial values) before execution of main() starts. here after main() function declared we write this line static int x=i; that's why it gives error . 2 votes 2 votes Sambhrant Maurya commented Jul 15, 2019 reply Follow Share #include <stdio.h> int main() { const int i=10; static int x=i; if(x==i) printf("Equal"); else if(x>i) printf("Greater"); else printf("Lesser"); return 0; } Ran this. Still giving the error "initializer element is not constant". 0 votes 0 votes Bikram commented Jul 15, 2019 reply Follow Share https://ideone.com/3gCzhK This code snippet also give error in devc++ IDE. Its not platform dependent. If we save the file like test.c ( means with any .c extension ) , this will give an error . A good reference for this https://stackoverflow.com/questions/5921920/difference-between-initialization-of-static-variables-in-c-and-c 0 votes 0 votes Please log in or register to add a comment.
Best answer 4 votes 4 votes static variable can be initialized with only constant expression.. so it will give compile time error. Bikram answered Jul 31, 2017 selected Jul 15, 2019 by Bikram Bikram comment Share Follow See all 2 Comments See all 2 2 Comments reply Priyansh Singh commented Nov 6, 2019 reply Follow Share what is we change that line 5th line: static int x=i; TO static int x; x=i; Then what will be o/p? 0 votes 0 votes ghostman23111 commented Apr 10, 2020 reply Follow Share Then it will print "Equal" because when we declare static variable it has "0" as default value. 0 votes 0 votes Please log in or register to add a comment.