C语言 将条件检查和变量赋值放在一个 if 语句中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6860327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Put condition check and variable assignment in one if statement
提问by deddebme
I am looking at some legacy C code and got confused, it is something like:
我正在查看一些遗留的 C 代码并感到困惑,它是这样的:
UINT A, B = 1;
if((A = B) == 1){
return(TRUE);
} else {
return(FALSE);
}
We all know there will be a compiler warning if we do if(A = B), but here it looks like the 'if' is checking A against 1, am I correct?
我们都知道如果我们执行 if(A = B) 会出现编译器警告,但这里看起来“if”正在检查 A 是否为 1,我说得对吗?
采纳答案by Ferdinand Beyer
First, it assigns the value of Bto A(A = B), then it checks if the result of this assignment, which is Aand evaluates to 1, is equal to 1.
首先,它将值分配B给A( A = B),然后检查此分配的结果(即A并且计算为1)是否等于1。
So technically you are correct: On the way it checks Aagainst 1.
所以从技术上讲,你是正确的:在检查的过程A中1。
To make things easier to read, the code is equivalent to:
为了使事情更容易阅读,代码等价于:
UINT A, B = 1;
A = B;
if(A == 1){
return(TRUE);
} else {
return(FALSE);
}
回答by Kerrek SB
Rather, your code is always assigning Bto A, and it is moreover checking whether the value of B(and thus also A) is equal to 1.
相反,您的代码总是分配B给A,而且它还会检查B(以及因此A)的值是否等于1。
There's nothing "legacy" about this, this is generally a pretty handy idiom if you need the result of an operation but also want to check for errors:
这没有什么“遗产”,如果您需要操作的结果但还想检查错误,这通常是一个非常方便的习惯用法:
int result;
if ((result = foo()) != -1)
{
printf("The result is: %i\n", result);
}
else
{
// panic
}
回答by noelicus
If you want to keep it on 1 line:
如果您想将其保留在 1 行:
if ((A = B), A == 1)
does the same thing.
做同样的事情。
回答by DreiBaer
We are trying to avoid if statements to make code more readable.
我们试图避免使用 if 语句以使代码更具可读性。
UINT A, B = 1;
bool fResult = false;
fResult = (A == B);
return(fResult);
And if there must be an condition to act on (not) equality, see this example.
如果必须有一个条件来实现(非)平等,请参阅此示例。
UINT A, B = 1;
bool fResult = false;
fResult = (A == B);
if(fResult)
{
doThis();
}
else
{
doThat();
}
return(fResult);
回答by Sander De Dycker
Correct. The value Ahas after the assignment will be compared to 1.
正确的。A赋值后的值将与 进行比较1。
This code sample is equivalent to just :
此代码示例相当于:
return (TRUE);

