C Programming - C Preprocessor - Discussion

Discussion Forum : C Preprocessor - Find Output of Program (Q.No. 5)
5.
What will be the output of the program?
#include<stdio.h>
#define CUBE(x) (x*x*x)

int main()
{
    int a, b=3;
    a = CUBE(b++);
    printf("%d, %d\n", a, b);
    return 0;
}
9, 4
27, 4
27, 6
Error
Answer: Option
Explanation:

The macro function CUBE(x) (x*x*x) calculates the cubic value of given number(Eg: 103.)

Step 1: int a, b=3; The variable a and b are declared as an integer type and varaible b id initialized to 3.

Step 2: a = CUBE(b++); becomes

=> a = b++ * b++ * b++;

=> a = 3 * 3 * 3; Here we are using post-increement operator, so the 3 is not incremented in this statement.

=> a = 27; Here, 27 is store in the variable a. By the way, the value of variable b is incremented by 3. (ie: b=6)

Step 3: printf("%d, %d\n", a, b); It prints the value of variable a and b.

Hence the output of the program is 27, 6.

Discussion:
41 comments Page 4 of 5.

Mangusta said:   1 decade ago
@Prashant.

I got that output in TurboC, then I re-launched it and compiled again, and this time it showed 27, 6.

Phaneendra said:   1 decade ago
I don't understand of 'b' value ?
how is it possible tell me please sir.
i expected 'b' value is only 3.
but answer is wrong.

Himansu said:   1 decade ago
What was output of :

#define PRODUCT(x) ( x * x )
main( )
{
int i = 3, j, k ;
j = PRODUCT( i++ ) ;
k = PRODUCT ( ++i ) ;
printf ( "\n%d %d", j, k ) ;
}

Sam said:   1 decade ago
Actually the behaviour is undefined.

In Turbo C k=++i + ++i; i.e., 2*i then i incremented two times.
In GCC k=++i + ++i; i incremented two times then 2*i;.

Travis said:   1 decade ago
Correct answer is 60 6, because CUBE (b++) is replaced by (b++*b++*b++) and therefore (3*4*5) = 60 while b increments three times.

Rajesh said:   1 decade ago
I also think that, value of b will be 5. Since Increment (b++) will start from 3 not from 4 (If it will ++b then b=6).

Amol said:   1 decade ago
@Pushkar Bhauryal. Please see the calculation:
@Neetesh.

In pre increment CUBE (++b); is proceed as B=3 initial value:

For first x in cube value ++b = 4.

For second X value is ++4 = 5.

For third x value is ++5 = 6.

Now the output = 4*5*6 = 150 //wrong.

= 4*5*6 = 120;

But compiler gives 150.

How it comes calculated value is 120 but actual is 150?

Anand said:   1 decade ago
Answer will be 60, 6 as 3*4*5, 6.

Pankaj said:   1 decade ago
Your answer in totally wrong. You can check by compiling. It is 60, 6.

Sudip said:   1 decade ago
Guys the correct answer is 60, 6. I compiled this program in other version i.e. GNU GCC version 4.7.2 and other too. And in this compiler its showing 27, 6! absolutely wrong.


Post your comments here:

Your comments will be displayed after verification.