C++ 条件语句

标签 c++

注:有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/

相关文章:

C++将字节二进制值转换为字符串

c++ - 初始化变量列表中的赋值顺序是否未定义?

c++ - 清除 RAM 中的内存?

c++ - 读入 vector 时排序

c++ - 在 C++/C 中声明变量时

c++ - 存储稀疏矩阵&高效迭代

c++ - IntelliSense 引擎无法正常运行的错误太多

c++ - 行排序数据到列排序数据的最快转换

c++ - 绕过虚拟模板函数以实现预期结果

c++ - 无法编译 mongo-cxx-driver