문제

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?

도움이 되었습니까?

해결책 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.

다른 팁

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))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top