Ade*_* M. 2 c loops if-statement variable-assignment
我正在用 C 做一个时间关键的应用程序。我想给一个变量赋值并同时在一个 while 循环中检查它的值,以便稍后在这个循环的主体中重用它。分配给变量的值由需要一些时间运行的函数返回。我知道我可以做这样的事情:
while (function_returning_int() <= foo) {
bar(function_returning_int());
}
Run Code Online (Sandbox Code Playgroud)
问题是这涉及调用同一个函数两次。我试着这样做:
while ((int thing = function_returning_int()) <= foo) {
bar(thing);
}
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误。我不明白为什么因为赋值运算符 ( =
) 返回分配的值。如何为变量赋值并在 while 循环中同时检查其值?
你很接近。您只需要在循环之外声明变量:
int thing;
while (( thing = function_returning_int()) <= foo) {
bar(thing);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
76 次 |
最近记录: |