Wednesday, 17 February 2010

What is the output of this tricky program?

Interesting problem from C Programming tricks:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

int
a=2,*f1,*f2;
f1=f2=&a;
*
f2+=*f2+=a+=2.5;
*
f1+=*f1+=a+=2.5;
cout<<"a = "<<a<<" *f1 = "<<*f1<<" *f2 = "<<*f2<<endl;

return
0;
}






What is the final value of a, *f1 and *f2. Choose one from below:
a) 18,18,18
b) 10,10,10
c) 72,72,72
d) 64,64,64
e) 26,26,26

The answer is...
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


6 comments:

  1. how did u do this?????

    ReplyDelete
  2. Do you mean, how did it come as 72? How about you show me how you calculated and what did you get and I will tell you how it becomes 72.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. ok sir...i got it
    how it comes out to be 72

    ReplyDelete
  5. a = 26 *f1 = 26 *f2 = 26

    for gcc

    ReplyDelete
  6. My guess is that compiler is making some optimisation. The gcc compiler is doing something like:
    2 + 2 + 2 + 2.5 = 8 (int)
    8 + 8 + 8 + 2.5 = 26 (int).

    The actual calculations should be

    8 + 4 + 2 + 2.5 = 16 (int)
    36 + 18 + 16 + 2.5 = 72 (int)

    ReplyDelete