(Created page with "<syntaxhighlight lang="c"> main() { int a=2; a=++a/a++; printf("%d", a; } </syntaxhighlight> {{Template:FB}} <disqus/> Category:Coding Questions")
 
Line 4: Line 4:
 
   int a=2;
 
   int a=2;
 
   a=++a/a++;
 
   a=++a/a++;
   printf("%d", a;
+
   printf("%d", b);
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
===Solution===
 +
 +
The answer to this is "Undefined". C standard says that the side effects of an operation (for b = ++a; modification of a is a side-effect) need to be completed only before the next [https://en.wikipedia.org/wiki/Sequence_point sequence point]. This relaxation is given so that the compiler would be able to generate the most optimal code (which run faster). But as a consequence, programmer shouldn't do a read and a write from a memory location within a sequence point or otherwise the result would be undefined.
 +
 +
So, in the statement a = ++a / a++;
 +
 +
++a / a++ can return only 1 value (3/3 = 1 or 3/2 = 1). But there is a side effect of post increment a++, which can happen anytime before the next sequence point. So, the answer can be 1+1 = 2 or simply 1. But as per C standard for these codes, the output is simply '''UNDEFINED'''
  
 
{{Template:FB}}
 
{{Template:FB}}

Revision as of 10:34, 12 December 2013

<syntaxhighlight lang="c"> main() {

  int a=2;
  a=++a/a++;
  printf("%d", b);

} </syntaxhighlight>

Solution

The answer to this is "Undefined". C standard says that the side effects of an operation (for b = ++a; modification of a is a side-effect) need to be completed only before the next sequence point. This relaxation is given so that the compiler would be able to generate the most optimal code (which run faster). But as a consequence, programmer shouldn't do a read and a write from a memory location within a sequence point or otherwise the result would be undefined.

So, in the statement a = ++a / a++;

++a / a++ can return only 1 value (3/3 = 1 or 3/2 = 1). But there is a side effect of post increment a++, which can happen anytime before the next sequence point. So, the answer can be 1+1 = 2 or simply 1. But as per C standard for these codes, the output is simply UNDEFINED





blog comments powered by Disqus

<syntaxhighlight lang="c"> main() {

  int a=2;
  a=++a/a++;
  printf("%d", a;

} </syntaxhighlight>





blog comments powered by Disqus