Jainendra
Jainendra

Reputation: 25143

Behaviour of preincrement operator in C program

I am running the following C code:

#define cube(x) (x*x*x)
void main()
{   
    int x=2,y;   
    y=cube(++x);            
    printf("%d %d",++x,y);    
}

I am expecting result as

6,60

But it is giving different result. I think I have misconception on pre-processor. I think the code will be similar to

void main()
{   
    int x=2,y;   
    y=++x*++x*++x;            
    printf("%d %d",++x,y);    
}

Please correct me if I am wrong.

I am interpretting the result to come as 3*4*5=60
but it is coming 125

Upvotes: 4

Views: 2960

Answers (4)

Jainendra
Jainendra

Reputation: 25143

The expression ++x*++x*++x will increment the value of x thrice i.e. the value of x would be 5 that is assigned to the expression. so 5*5*5 = 125 is the output. Again the value differs depending upon the architecture of the compiler.

Upvotes: -1

USER_NAME
USER_NAME

Reputation: 1037

Output of this program differs with compilers, operating systems and even with the different versions of same compiler because output depends on the order of execution of sub-expressions.
I compiled it with Visual Studio: o/p is 125.
When I compiled with gcc: o/p is 80.
So you can not predict the output.
And I dont know why people ask these type of questions(those dont have a defined out come) in interviews?

Upvotes: -1

Mohanraj
Mohanraj

Reputation: 4200

The preprocessor take the expression what we are giving, so that, for your c code, initially x=2, so that while executing macro,

First it takes two values to multiply it, then takes third value multiply with the result, so the sequence should be,

++x * ++x => 3(first increment), 4(again for next increment), so now x value is 4, according to expression

4 * 4 => 16,

Again for next increment x => 5, so according to your expression result should be,

16 * 5 => 80

So now total result of multiplication is 80, and the x value is 5.

Upvotes: -1

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

You defined a macro, which works as a simple string substitution, so that the presented translation is correct.

However, the order of execution of subexpressions is undefined and they can be, for example, interleaved and this makes the undefined behaviour.

Upvotes: 5

Related Questions