[英]for loop init variable scope between c++, java, C#
我在理解這4種語言C,C ++,C#,Java中for循環的初始變量范圍不同時遇到問題
我知道的是,在C#中: for ( int i = 1; i<=5; i++)
在這里, i
是局部變量,不會出現在for括號的范圍之外。 所以,我可以多次使用它在多個塊,還Java是這樣的,但我是知道,C和C ++不一樣, i
在for ( int i = 1; i<=5; i++)
的聲明不在里面的水平。
我試圖運行以下代碼來檢查我的想法是否正確:
舊C:
// old C: error: 'for' loop initial declarations are only allowed in C99 or C11 mode
// note: previous definition of 'i' was here
for ( int i = 0; i<=5; i++) printf ("%d",i);
for ( int i = 5; i>=0; i--) printf ("%d",i);
printf ("%d",i);
C99:
// error: 'i' undeclared (first use in this function)
for ( int i = 0; i<=5; i++) printf ("%d",i);
for ( int i = 5; i>=0; i--) printf ("%d",i);
printf ("%d",i);
舊的C ++:
// error: name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]
for ( int i = 0; i<=5; i++) cout << i << endl;
for( int i = 5; i>=0; i--) cout << i << endl;
cout << i;
C ++ 11:
for ( int i = 0; i<=5; i++) cout << i << endl;
for( int i = 5; i>=0; i--) cout << i << endl;
cout << i; error: 'i' was not declared in this scope
Java的:
for ( int i = 0; i<=5; i++) System.out.println(i);
for( int i = 5; i>=0; i--) System.out.println(i);
System.out.println(i); // error: 'i' was not declared in this scope
C#:
for ( int i = 0; i<=5; i++) Console.Write(i); // 0 1 2 3 4 5
Console.WriteLine("");
for ( int i = 5; i>=0; i--) Console.Write(i); // 5 4 3 2 1 0
Console.WriteLine(i); // error: 'i' was not declared in this scope
我認為C99,C ++ 11,C#,Java是相同的,而區別僅在於舊的C和C ++。
這是正確的嗎?
謝謝
不完全的。
只有標准的C ++(在1998年的ANSI標准成為ISO標准之前)的行為與您對“舊的C ++”的描述相同。 大約在1995年,標准草案從內存中發生了變化,當時的大多數編譯器都采用了這種變化。 在此之前,一些C ++編譯器將變量的范圍限制為循環,作為特定於供應商的擴展。
來自1999年標准的C,標准C ++,Java和C#都將在for循環中聲明的變量的范圍限制為僅該循環。
1989年(ANSI)和1990年(ISO)的標准C,1995年之前的標准C(包括K&R)和標准C ++都沒有。 正如juanchpanza在評論中指出的那樣,C89 / C90完全不允許在循環初始化內進行變量聲明。
實際上,這對於標准的C ++來說並不完全正確。 因為某些編譯器存在關於循環變量的問題, i
可以在for循環塊之外使用該循環變量而無需重新聲明。 我的意思是
// error: name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]
for ( int i = 0; i<=5; i++) cout << i << endl;
for( int i = 5; i>=0; i--) cout << i << endl;
cout << i;
在該編譯器中這可能不是錯誤。 而且您可能會在文件中看到此宏以進行保護。
#define for if(0) {} else for
在那之后,現在i
在else塊中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.