views:

112

answers:

5
 #include<stdio.h>

int main(void)
{
   static int i=i++, j=j++, k=k++;
   printf("i = %d j = %d k = %d", i, j, k);
   return 0;
}

Output in Turbo C 4.5 :

i = 0 j = 0 k = 0

In gcc I'm getting the error:

Initializer element is not constant

Which one is logically correct ? I'm in bit confusion..

A: 

I would guess GCC is correct here. An initializer should not be a variable. You try to initialize a variable with itself, before it is defined.

I guess Turbo C "reasons", that i is after all static variable, and hence should have value zero (as all static variables have default), then goes on to ignore the ++ operation.

Amigable Clark Kant
@Amigable Clark Kant Static variables are automatically initialised to 0.
Parixit
@Parixit, oops i missed that keyword.
Amigable Clark Kant
A: 

buddy u havent initialized the variables and u r incrementing them, as u have not initialized any variable it will take garbage value and i dont think so incrementing any garbage value is the correct thing to do. So please first initialize the variables and then increment them. U will get the correct answer.

Prateek
@Prateek Hey ..I think u missed the static keyword..
Parixit
+11  A: 
Cirno de Bergerac
+1 for the last sentence.
Ruel
+1 for the reference
Elenaher
Aboelnour
+1 for the ref.
Amigable Clark Kant
+4  A: 

I know this is not an answer, but still, why use a complex example for the test?

Okay, let's simplify everything:

#include<stdio.h>
int main(void)
{
   static int i;
   printf("i = %d", i);
   return 0;
}

Output:

i = 0

But what if... ?

 #include<stdio.h>
 int main(void)
{
   static int i=i;
   printf("i = %d", i);
   return 0;
}

Output:

prog.c: In function ‘main’:
prog.c:4: error: initializer element is not constant
wok
@wok thnx buddy...
Parixit
+1  A: 

GCC is correct here.

static variables are initialised (at program load time) to the value specified in the initialiser (or to 0 if no initialiser was given). As this initialisation happens before the program is started, initialisers for static variables must be compile-time constants. An expression containing the ++ operator is clearly not a constant expression.

Bart van Ingen Schenau