for loop

Iai Masafumi ax iai at axelspace.com
Mon Dec 5 23:43:34 CET 2011


Hello,

Isn't this behavior of FOR loops confusing? I accidentally wrote a code
like below. The same variable i is used for both of the nested for loops.

I don't think it is a bug. Scilab is working as designed.  Yet, probably
it is good to throw an error (which C# does), or at least warning? Or
two i's can be treated separately according to their scopes (which C++
does)?

Just an idea.

-- Code -----------------
for i=1:3,
  mprintf("A%d\n", i),
  for i=4:5,
    mprintf("B%d\n", i),
  end,
  mprintf("C%d\n", i),
end
------------------------

-- Output --------------
A1
B4
B5
C5
A2
B4
B5
C5
A3
B4
B5
C5
-----------------------

--  C# ---------------------
            int[] myArray = new int[] { 1, 2, 3 };
            foreach (int x in myArray)
            {
                Console.WriteLine("A" + x);
                int[] myArray2 = new int[] { 4, 5 };
                foreach (int x in myArray2)   // <---- ERROR
                {
                    Console.WriteLine("B"+x);
                }
                Console.WriteLine("C"+x);
-----------------------------
-- C++ -----------------------
	for( int i=1; i<=3; i++ ) {
		std::cout << "A" << i << std::endl;
		for( int i=4; i<=5; i++ ) {
			std::cout << "B" << i << std::endl;
		}
		std::cout << "C" << i << std::endl;
	}
--------------------------------
I use Visual Studio 2010 for C# and C++.




More information about the users mailing list