没有花括号的for循环是做什么的? [英] What does a for loop without curly braces do?

查看:322
本文介绍了没有花括号的for循环是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我的问题是什么一个for循环没有任何大括号左右呢?所以据我所知,在if语句中,只有代码的第一行被执行。所以在for循环中它是如何工作的?我没有真正理解没有大括号和大括号的循环的概念。我想用一段代码解释会有所帮助。顺便说一下,这是在C中。这里有一个代码,我一直在寻找作为参考。

  int main(int argc,char * argv [])
{
int i;
int count = 0;
for(i = 0; i <5; i ++)
count ++;
printf(count的值是:%d \\\
,count);

返回0;





$ b在这种情况下,我看到没有花括号,所以我假设它将继续迭代第一个语句直到i < 5一旦我不少于5,它什么都不做,但是当我测试代码时,我得到它也最终打印printf语句。我以为没有花括号的循环只执行第一行代码?如果没有花括号,只有循环定义之后的第一条语句被认为是属于这个类型的。循环体。



请注意,在你的例子中, printf 只被调用一次。虽然它的缩进符合上一行,那是一条红色的鲱鱼 - C不在乎。它对我说的是,编写代码的人可能会忘记大括号,并且将 printf 语句作为循环体的一部分。 / p>

如果语句写了一行,那么我只会忽略花括号:

  if(condition)statement; 
do_something_else();

在这里,没有缩写来解释第二行的语句是否应该属于到如果的主体。在阅读本文时,您可能会更有信心,正如预期的那样。


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.

解决方案

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.

这篇关于没有花括号的for循环是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆