![](/img/trans.png)
[英]Why the absence of curly brackets after FOR loop in finding factorials in C
[英]why the absence of curly brackets after for loop
我是初學者,請你告訴我為什么程序中的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);
}
允許不為單行添加括號。 但是我強烈建議不要這樣做。 這是一個着名的錯誤 ,可能是不使用括號的結果。
例如,如果你寫
if(test)
foo();
后來需要第二個函數調用,你可能會犯寫錯誤
if(test)
foo();
bar();
這不是你想要的。
如果你從頭開始使用括號並寫
if(test) {
foo();
}
你沒有這個問題:
if(test) {
foo();
bar();
}
如果只有一個語句需要循環,即如果循環體只是一個語句,則可以省略大括號{ }
。 這是遞歸地工作,例如
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]);
}
}
}
如果您的代碼由一行組成,則可以不帶括號編寫。
這不僅適用於循環,它也適用於有條件的條款一樣if
if else
或else
例如:
if(a == b){
a++;
}
是相同的
if(a == b)
a++;
您好,歡迎來到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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.