它们非常受欢迎,但我从来没有使用它们的“球”。
基本上,我永远不知道他们会在哪里停下来。他们只是执行下一行代码吗?
如果我这样做:
for(int i = 0; i<10; i++)
if(i % 2 == 0)
//this is included in the for loop and the if statement
function();
// is this?
function2();
// where does it stop?
function3();
包括else语句怎么样?
for(int i = 0; i<10; i++)
if(i % 2 == 0)
//this is included in the for loop and the if statement
function();
else
// is this run as part of the for loop? even though theres a semi colon before it?
function2();
如果我这样做......
if((int)1 == (int)1) function1(); function2(); function3(); function4();
所有代码都运行了吗?
这是怎么回事?
if((int)1 == (int)1) function();
function2();
function3();
它是否会运行到下一个;
?
谢谢汤姆
答案 0 :(得分:9)
if / else / for / foreach / while / do只会执行下一个语句,如果它没有{}。这包括:
if((int)1 != (int)1) function1(); function2(); function3(); function4();
第一个函数不会运行,因为if不符合,其他函数不包括在if
中一般规则总是使用{},它使代码更清晰可读
答案 1 :(得分:2)
取决于语言。
在许多语言中,基本上大多数C派生词,if语句只执行下一个语句或语句块。 (事实上,在大多数基础语法中,语句块会减少为单个语句!)以下语言(我知道)就是这样:
在您的第一个代码示例中,只有function()
绑定到if条件。
在Perl中,设计师决定强制阻止if-statements。但是对于单语句if,有语句后缀。所以以下是等价的:
# if-statement preceding block...
if (x == 5)
{
print "x is 5";
}
# if-statement as a suffix conditional to one statement (line break for readability)
print "x is 5"
if x == 5;
# Equivalent to the second, because "do BLOCK;" can be used anywhere a
# simple statement can be used
do
{
print "x is 5";
} if x == 5;
Python的工作方式有点像你最初的例子所暗示的那样:缩进就是一切。
if (x == 5):
print "x is 5"
print "This is always printed"
答案 2 :(得分:1)
这些是等价物:
for(int i = 0; i<10; i++) {
if(i % 2 == 0) {
//this is included in the for loop and the if loop
function();
}
}
// is this?
function2();
// where does it stop?
function3();
...
for(int i = 0; i<10; i++) {
if(i % 2 == 0) {
//this is included in the for loop and the if loop
function();
}
else {
// is this run as part of the for loop? even though theres a semi colon before it?
function2();
}
}
...
if((int)1 == (int)1) {
function1();
}
function2();
function3();
function4();
...
if((int)1 == (int)1) {
function();
}
function2();
function3();
...
总之,{}之间的任何内容都被视为单个语句 - 反之亦然。
答案 3 :(得分:1)
如果你想使用“内联”状态,你可以这样做:
bool greaterthan(int a, int b){
return a>b ? true:false;
}
这基本上意味着如果a> b,则返回true,否则返回false。这也可以用于许多其他方式!
答案 4 :(得分:0)
执行下一个逻辑评估“块”,这通常意味着执行下一个“语句”(以“;”结尾)。
程序流程命令被视为用于评估目的的语句。
答案 5 :(得分:0)
所有基于C语言(PHP语法基于C语言)的工作方式如下:
for (foo1();foo2();foo3())
operation1();
operation2();
以上只执行operation1()
if (foo())
operation1();
operation2();
以上只执行operation1()
答案 6 :(得分:0)
如果您没有使用复合语句({}所附的语句),则只包括第一行
for(int i=0; i<10; i++)
if(i==5) // included in loop
printf("%d\n",i); // included since if is included.
else
prinf("Not Five"); // Included if is included
如果statments,if-else语句,for循环,while循环等被视为一行
类似地
for(int i=0; i<10; i++)
function1(); // included
function2(); // not included
希望你理解。
答案 7 :(得分:0)
我想指出不推荐使用这种语法,因为它很容易适应逆火。请采取以下措施,例如:
if (true)
// not working properly. Exclude it for now
// foo()
bar();
在这种情况下,bar()得到执行,因为它是下一个逻辑语句,即使它显然不是要运行的预期语句。这有可能引起巨大的麻烦,所有这一切都来自一个简单的评论和结构不合理的“如果”
答案 8 :(得分:-1)
取决于您使用的语言。只是学习语言。