简体   繁体   English

奇怪的C算术行为

[英]Strange C arithmetical behavior

I have a problem with this piece of C code: 我对这段C代码有疑问:

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! 它应将h设置为640,但应将其设置为0!

You can see it running here: http://ideone.com/zBZSsr 您可以看到它在这里运行: http : //ideone.com/zBZSsr

Any idea about this strange behavior? 对这种奇怪的行为有任何想法吗? Am I doing something wrong? 难道我做错了什么?

The max macro in the example you linked needs an extra pair of parentheses. 您链接的示例中的max宏需要一对额外的括号。

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. 从bool到int进行了一些隐式转换,然后又返回,这导致始终为true的情况,因此您将获得true分支,该分支只是0。

Your macro should be: 您的宏应为:

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

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. 在定义周围添加(),您的计算将是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM