注:有python背景的学习C++背景
查看下面代码的最后一个 if 语句: if 语句后 i=1 是什么意思。 查看最后的 else 语句。 else 语句后的 i=0 是什么意思? 他们为什么在那里
#include <stdio.h> // preprocessor command
int foo(int x) // function definition
{
return x+1; // return expression value
}
int main() // this is where all C programs start
{
int i = 0; // variable definition + init.
while (i < 10)
{ // loop + condition
i = i+1; // expression + assignment
printf("%d ", foo(i)); // function calls, output
}
if (i >= 10) i = 1; // conditional code execution
else i = 0;
return i; // return result, exit function
}
最佳答案
在您的示例中,i=1
是未包含在 if
语句中的赋值语句,不是条件代码。相当于
if (i >= 10) // conditional code
i = 1; // will execute if i>=10
或更清晰
if (i >= 10) // conditional code
{
i = 1; // will execute if i>=10
}
如果你愿意,尽管不推荐,你可以将所有代码写在一行中。
你应该知道 indent style不同语言的:
Indentation is not a requirement of most programming languages, where it is used as secondary notation. Rather, programmers indent to better convey the structure of their programs to human readers. In particular, indentation is used to show the relationship between control flow constructs such as conditions or loops and code contained within and outside them. However, some programming languages (such as Python and Occam) use the indentation to determine the structure instead of using braces or keywords.
关于C++ 条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105658/