【问题标题】:why the absence of curly brackets after for loop为什么for循环后没有大括号
【发布时间】:2014-05-07 18:18:13
【问题描述】:

我是初学者,请你告诉我为什么程序中的for循环后面没有大括号{ }。我已对此问题发表评论。

void main()
{
    int a[50],n,count_neg=0,count_pos=0,I;

    printf("Enter the size of the array\n");

    scanf("%d",&n);

    printf("Enter the elements of the array\n");

    for (I=0;I < n;I++)          /* i dont understand why no {} occuerred after this for loop please explain*/
        scanf("%d",&a[I]);

    for(I=0;I < n;I++)
    {
        if(a[I] < 0)
          count_neg++;
        else
         count_pos++;
    }

    printf("There are %d negative numbers in the array\n",count_neg);
    printf("There are %d positive numbers in the array\n",count_pos);
}

【问题讨论】:

  • 还有你为什么提到像count number of negative and positive number in an array这样的主题行?因为您的问题与 for 循环理解有关。
  • 是的,这并不反映您的实际怀疑;请给出适当的标题和描述。

标签: c arrays for-loop


【解决方案1】:

如果只有一条语句需要循环,即如果循环体只是一条语句,则可以省略大括号 { }。这可以递归地工作,例如

for(i = 0; i < n; ++i)
   for(j = 0; j < m; ++j)
      for(k = 0; k < l; ++k)
        process(v[i][j][k]);

相同
for(i = 0; i < n; ++i)
{
   for(j = 0; j < m; ++j)
   {
      for(k = 0; k < l; ++k)
      {
        process(v[i][j][k]);
      }
   }
}

【讨论】:

    【解决方案2】:

    如果你的代码只有一行,你可以不加括号。

    这不仅适用于循环,也适用于if if elseelse 等条件子句

    例如:

    if(a == b){
        a++;
    }
    

    一样
    if(a == b)
        a++;
    

    【讨论】:

      【解决方案3】:

      单行可以不加括号。但是我强烈建议不要这样做。这是a famous bug,这可能是不使用括号的结果。

      例如,如果你写

      if(test)
         foo();
      

      以后需要第二个函数调用你可能会写错误

      if(test)
         foo();
         bar();
      

      不是你想要的。

      如果你从头开始使用括号并写

      if(test) {
         foo();
      }
      

      你没有这个问题:

      if(test) {
         foo();
         bar();
      }
      

      【讨论】:

        【解决方案4】:

        您好,欢迎来到 StackOverflow! :)

        我一般不明白你的问题,但我还是会告诉你以下内容: 在编程中,开始和结束括号 { } 用于标识代码块,该代码块将从开始括号 { 不间断地执行,直到结束括号 }。代码块用于将一段代码与另一段代码隔离开来。

        示例 1:

        void Function1()
        {
        
          void Function2()
          {
            // Calculate
            // Long Stuff
            // Complicated
            // Atom Bombs exploding
        
          } // Close Function2
        
          void Function3()
          {
            // Do 
            // Some
            // Other
            // Evil
            // Stuff
        
          } // Close Function3
        
        }// Close Function1
        
        void Function3()
        {
        
          InnerFunction(); // This will execute Function3, but without going to Function3,  
                           // because the code of Function2 is ISOLATED with {} from the code of Function3
        
        }// Close Function2
        

        【讨论】:

          猜你喜欢
          • 2021-02-14
          • 2017-10-28
          • 2014-12-05
          • 1970-01-01
          • 1970-01-01
          • 2020-12-02
          • 2012-12-09
          • 2020-10-03
          • 1970-01-01
          相关资源
          最近更新 更多