in Programming edited by
408 views
1 vote
1 vote

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;
} 

 

  1.   Equal
  2.   Greater 
  3.   Lesser
  4.   Compilation Error
in Programming edited by
by
408 views

4 Comments

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
2

#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
0
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
0

1 Answer

4 votes
4 votes
Best answer
static variable can be initialized with only constant expression..
so it will give compile time error.
selected by

2 Comments

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
0
Then it will print "Equal" because when we declare static variable it has "0" as default value.
0
0
Answer:

Related questions