简体   繁体   English

在for循环中添加{-}:c编程

[英]adding { - } in a for loop : c programming

the program runs fine and clear, but i just wanted to ask why didnt we add { - } in the beggining and end of the for loop ? 程序运行良好且清晰,但是我只想问为什么我们在for循环的开始和结尾处不添加{-? the program runs fine without adding them but when i tried to add { - } in the for loop the prgram didnt run fine, arent we suppose to add { - } in ever begging and end of every loop ? 程序可以正常运行而不添加它们,但是当我尝试在for循环中添加{-}时,prgram不能正常运行,难道我们想在每次循环和每次循环结束时都添加{-}吗? and why did the program run fine without them and didnt run fine with them ? 为什么程序在没有它们的情况下运行良好,而在没有它们的情况下运行良好?

int c, first, last, middle, n, search, array[100];

   printf("Enter number of elements\n");
   scanf("%d",&n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);

   printf("Enter value to find\n");
   scanf("%d",&search);

   first = 0;
   last = n - 1;
   middle = (first+last)/2;

   while( first <= last )
   {
      if ( array[middle] < search )
         first = middle + 1;    
      else if ( array[middle] == search ) 
      {
         printf("%d found at location %d.\n", search, middle+1);
         break;
      }
      else
         last = middle - 1;

      middle = (first + last)/2;
   }
   if ( first > last )
      printf("Not found! %d is not present in the list.\n", search);

Without braces it takes ONE statement as its scope 没有花括号,它将ONE语句作为其范围

like 喜欢

for ( c = 0 ; c < n ; c++ )
 scanf("%d",&array[c]);

Equivalent of 相当于

 for ( c = 0 ; c < n ; c++ )
{
  scanf("%d",&array[c]);
}

A loop executes the statement immediately after it in a loop. 循环在循环后立即执行该语句。 What is a statement? 什么是陈述? It can be: 有可能:

A piece of code ended with ; 一段以结尾的代码; .

A block of code started with { and ended with } . 一段代码以{开头,以}结尾。

Your for-loop 你的循环

for ( c = 0 ; c < n ; c++ )
  scanf("%d",&array[c]);

uses the first definition of statement, but you could also write it as 使用语句的第一个定义,但是您也可以将其写为

for ( c = 0 ; c < n ; c++ )
{
  scanf("%d",&array[c]);
}

and it should work fine. 它应该可以正常工作。

Informally: The for-loop has a one-statement body. 非正式地:for循环具有一个语句主体。 To use multiple statements, you nest them in a block-statement. 要使用多个语句,请将它们嵌套在一个语句块中。

如果块中只有一条语句,则括号是可选的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM