What does a for loop without curly braces do?

不想你离开。 提交于 2019-12-28 03:10:09

问题


Hi so basically my question is what does a for loop without any curly braces around it do? So from what I know, that during an if-statement only the first line of the code is executed. So in a for loop how does it work? I don't really understand the concept of a loop without the braces and with the braces. I guess an explanation with a piece of code would help. This is in C by the way. Here's a code I've been looking at as a reference.

int main(int argc, char* argv[])
{
  int i;
  int count = 0;
  for (i = 0; i < 5; i++)
    count++;
    printf("The value of count is: %d\n", count);

  return 0;
}

In this case, I see that there is no curly braces, so I am assuming that it will just keep iterating the first statement until i < 5 and once i is not less than 5 it doesn't do anything, but when I tested the code I get that it also ends up printing the printf statement. I thought that a loop without curly braces executed only the first line of code? Or am I missing something here.


回答1:


Without curly braces, only the first statement following the loop definition is considered to belong to the loop body.

Notice that in your example, printf is only called once. Though its indentation matches the previous line, that's a red herring – C doesn't care. What it says to me is that whoever wrote the code probably forgot the braces, and intended the printf statement to be part of the loop body.

The only time I would leave out the curly braces is when writing a one-line if statement:

if (condition) statement;
do_something_else();

Here, there's no indentation to introduce ambiguity about whether the statement on the second line is actually supposed to belong to the body of the if. You would likely be more confident when reading this that it's working as intended.




回答2:


If the for-loop does not have braces, it will execute the next statement. The syntax is essentially

for (<initialization>;<condition>;<increment>) <statement>;

The "statement" part can be anything. It could be a simple count++; or it could be an 'if'/'if-else' statement, it could even be another for-loop without the braces!

So in this case, the code is similar to:

for (i = 0; i < 5; i++) {
    count++;
}
printf("The value of count is: %d\n", count);


来源:https://stackoverflow.com/questions/26289546/what-does-a-for-loop-without-curly-braces-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!