Question

I have a problem with this piece of C code:

int y = 0, h = 640, ih = 640;
h = y + h - max(0, (y + h) - ih);

It should set h to 640, but instead it is setted to 0!

You can see it running here: http://ideone.com/zBZSsr

Any idea about this strange behavior? Am I doing something wrong?

Was it helpful?

Solution 2

your code gets preprocessed to

h = y + h - ((0) > ((y + h) - ih)) ? (0) : ((y + h) - ih);

the problem is that + and - has priority over ?: operator.

#define max(x, y) ((x) > ((y)) ? (x) : (y))

add () around the defines and your computation will be correct.

OTHER TIPS

The max macro in the example you linked needs an extra pair of parentheses.

You have:

#define max(x, y) ((x) > (y)) ? (x) : (y)

In your example, this expands to:

h = y + h - ((0) > ((y+h)-ih)) ? (0) : ((y+h)-ih);

I believe the operator precedence means that everything on the left is subsumed into the condition expression for the ternary operator. There's some implicit conversion from bool to int and back again, resulting in an always-true condition, so you then get the true branch, which is simply 0.

Your macro should be:

#define max(x, y) (((x) > (y)) ? (x) : (y))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top