vendredi 12 juin 2015

for loop init variable scope between c++, java, C#

I have a problem in understanding the difference in scope of initial variable of for loop in those 4 languages C, C++, C#, Java

what i was know that in C#: for ( int i = 1; i<=5; i++) here, i is a local variable dose not appear out the scope of for brackets. so i can use it multiple times in multiple blocks, also Java like that, but what i was know that c and c++ not the same as i in for ( int i = 1; i<=5; i++) is declared on the level of for not in inside it.

i tried to run the below code to check if my thought correct or not:

old 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);

old 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

I think C99, C++11, C#, Java are same while the diffrence only in old C and C++.

Is this right or not ??

Thanks

Aucun commentaire:

Enregistrer un commentaire