-5
int p=4, s=5;
int m;

m = (p=s) * (p==s);
printf("%d",m);

How is this expression evaluated?

What will be the value of m?

How do parenthesis change the precedence of operators in this example?

I am getting m=4 in Turbo C.

dbush
  • 205,898
  • 23
  • 218
  • 273

2 Answers2

1

Is this a code fragment that actually came up in your work, or is it an assignment someone gave you?

The expression contains two parts:

p=s     /* in this part p's value is assigned */

p==s    /* in this part p's value is used */

So before we can figure out what the value of the expression is, we have to figure out: does p's value get set before or after it gets used?

And the answer is -- I'm going to shout a little here -- WE DO NOT KNOW.

Let me say that again. We simply do not know whether p's value gets set before or after it gets used. So we have no way of predicting what value this expression will evaluate to.

Now, you might think that precedence will tell you whether p gets set before or after it gets used. But it turns out that, no, in this case precedence does not tell you whether p gets set before or after it gets used.

You might think that associativity will tell you whether p gets set before or after it gets used. But it turns out that, no, in this case associativity does not tell you whether p gets set before or after it gets used, either.

Finally, you might think that I'm wrong, that precedence and/or associativity have to be able to tell you what you need to know, that there has to be a way of figuring out what this expression does. But it turns out that I'm right: there is no way of figuring out what this expression does.

You could compile it and try it, but that will only tell you how the compiler you're using today chooses to evaluate it. I guarantee you that there's another compiler out there that will evaluate it differently.

You might ask, which compiler is right? And the answer is, they're both right (or at least, neither of them is wrong). As far as the C language is concerned, this expression is undefined. So there's no right answer, and your compiler isn't wrong no matter what it does.

If this is code that came up in your work, please delete it right away, and figure out what you were really trying to do, and figure out some cleaner, well-defined way of expressing it. And if this code is an assignment, your answer is simply: it's undefined. (If your instructor believes this expression has a well-defined result, you're in the unfortunate position of having an instructor who doesn't know what he's talking about.)

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
0

You're reading and writing the variable p multiple times in the same expression without a sequence point, which means the compiler is free to evaluate the two sub-expressions in any order.

This results in undefined behavior, meaning the program's behavior is unpredictable.

dbush
  • 205,898
  • 23
  • 218
  • 273