Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c - What does a for loop without curly braces do?

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
", 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...