-3

I am skipping header files and void main...
Code 1:-

int a = 5 , c ;
c = a++ + ++a + a++;
a = 5;
printf("%d %d",a++ + ++a + a++ , c);
___________________________________________________

Outputs:-
TCC:- (Yes Borlands 3.0 or whatever it is called one for DOS-blue environment)
19 18
19 = how ? 5+7+7 and if yes (definitely compared to GCC output) but why not 18?

18 = 6+6+6 ? (c assignment code equivalent to
a++;
c=a+a+a;
a++;
a++;) right ?
and why 19 18 ? two different values for exactly same code ?
GCC:-
19 19
19 both 5+7+7 ? makes sense..

Now , Code 2:-

int a = 5 , c ;
c = ++a + ++a + ++a;
a = 5;
printf("%d %d",++a + ++a + ++a, c);
_________________________________________________

TCC:-
24 24
24 with same logic 8+8+8(c assignment code equivalent to
a++;
a++;
a++;
c=a+a+a;
) and a = 8 ;

GCC:-
22 22
22 ? how ? by normal logic 6 + 7 + 8 = 21 but output 22 ?
then 6+8+8 and if yes how ?

  • http://stackoverflow.com/questions/6067722/a-weird-behavior-of-c-compilers-gcc-and-turbo That may be relevant. It is (or at least, it seems to be) to do with an undefined order of operations taking place. – Luke May 01 '15 at 03:45
  • http://meta.stackexchange.com/questions/22232/are-expletives-cursing-swear-words-or-vulgar-language-allowed-on-se-sites/22233#22233 – Levi May 01 '15 at 03:46
  • @Luke it is bit relevant , yet i am not changing value of 'a' between two arguments of function call 'printf()' , 'c' is calculated separately and then 'a' is reset to 5. – Ninad Sheth May 01 '15 at 03:59

1 Answers1

-1

Different compilers execute expression in their own manner. Compilers execute statements with Optimization Ideally, we should not compare behaviour of compiler versions i.e. TCC, GCC, Borland c etc

The order of execution may change from compiler to compiler depending on optimization techniques

Reference answer : Very Nice Explaination

For exam point of view, we should follow textbook standard in this type of questions

Community
  • 1
  • 1
Kushal
  • 8,100
  • 9
  • 63
  • 82
  • so it is possible that optimization for 'c = a++ + ++a + a++;' is different than optimization of 'a++ + ++a + a++' in function call wrt TCC (even though calculation is exactly same) and hence two ans viz. 18 19 are generated ? – Ninad Sheth May 01 '15 at 04:33
  • yes.. because at time of executing `second` statement, compiler may have taken different order keeping optimization techniques in mind – Kushal May 01 '15 at 04:35
  • The code the OP has exhibits Undefined Behavior. – Spikatrix May 01 '15 at 06:07