How do you use an existing variable within one or more for loops?
Asked Answered
S

8

7

I'm working my way through Head First C#, and I'm a bit confused on my current exercise. They state:

If you declare a variable inside a for loop--for (int c = 0; ...)--then that variable's only valid inside the loop's curly brackets. So if you have two for loops that both use the variable, you'll either declare it in each loop or have one declaration outside the loop. And if the variable c is already declared outside of the loops, you can't use it in either one.

This sounds contradictory to me, almost like saying you can only use it outside if you declare it outside, but if you declare it outside you can't use it.

So can you, or can't you? I tried declaring c in two separate for loops and it worked fine, but when declaring c outside of the for loops I couldn't find any way to reference the variable c inside both for loops while it's also declared outside, whether I was trying to change its value or not. This isn't required for the exercise, I'm just trying to soak up every bit of knowledge I come across and trying to go beyond the material.

The book may be confusing me, so if this isn't possible and is completely unnecessary, just let me know, thanks!

Susansusana answered 7/11, 2010 at 9:12 Comment(1)
I appreciate the help everyone, that clears it up!Susansusana
S
10

The issue is one of scoping. Read here for some details on how variable scoping works in C#.

If a variable is declared outside a loop, you can't re-declare it inside:

BAD:

int c = 0;
for(int c = 0; c < list.Count; c++) // Error!
{

}

OK:

Declared outside, used inside:

int c = 0;
for(c = 0; c < list1.Count; c++)
{
}

for(c = 0; c < list2.Count; c++)
{
}

Declared inside two loops:

for(int c = 0; c < list1.Count; c++)
{
}

for(int c = 0; c < list2.Count; c++)
{
}
Sellars answered 7/11, 2010 at 9:14 Comment(3)
@Philipp - same difference. The issue is a scoping one. Answer updated to use for loops.Sellars
I found that with your second answer, you can omit everything before the first semicolon as a shorthand syntax. Makes more sense to me than having to re-assign the 0.Titicaca
@Titicaca - that is short for the same - .net would default the value of the int to 0.Sellars
S
3

You can either do

  int i;
  for (i = 0; i < 3; i++)
    foo(i);
  for (i = 0; i < 5; i++)
    bar(i);

or

 for (int i = 0; i < 3; i++)
    foo(i);
 for (int i = 0; i < 5; i++)
    bar(i);

but not

int i;
for (int i = 0; i < 3; i++) //error
  foo(i);
for (int i = 0; i < 5; i++)
  bar(i);
Stichous answered 7/11, 2010 at 9:18 Comment(0)
B
1

I think they mean the following.

You can do this. What happens hear is that you've declared a variable outside of the loop and are using it. The problem though is that you may overwrite an existing value which you need to use somewhere else.

int i = 0;

for (i = 0; i < 100; i++)
{
    // Do something
}

What you really can't do is this. Here you are re-using the variable from the outer for in the inner for.

for (int i = 0; i < 100; i++)
{
    for (i = 0; i < 100; i++)
    {
        // Do something
    }
}
Babble answered 7/11, 2010 at 9:15 Comment(0)
L
1

The statement is indeed confusing, if I understand it correctly, according to the text I should not be able to do this:

int i;
for (i = 1; i < 10; i++) { }

for (i = 0; i < 20; i++) { }

But I can, and this is clearly valid. I think what the text means is "you can't re-declare it in either one" instead of "you can't use it in either one".

Luo answered 7/11, 2010 at 9:24 Comment(0)
U
1

The concept here is Scope. A variable is declared within some scope and cannot be accessed outside of it. This helps define the lifetime of a variable as well as control access to it. A variable can be declared within a class, a method, or a conditional scope within a method such as within an if statement or a for loop.

One easy way to think of scope is that you can access a variable
within the pair of curly braces { ... } it lives under.

Here's an example:

    public class TestClass
    {
        int p;  // p's is in the 'TestClass' scope

        public void TestFunction1()
        {

            Console.WriteLine(p);   // OK, p in class scope

            //  a lives in the 'TestFunction' scope
            int a = 1; // Declared outside of any loop.

            for (int i = 0; i < 10; i++)
            {
                //  i lives in the scope of this for loop
                Console.WriteLine(i);
                //  a is still accessible since this for loop is inside TestFunction1
                Console.WriteLine(a);
            }
            Console.WriteLine(a); // OK, in scope
            //Console.WriteLine(i); // Error, i out of scope

            //  j also lives in the TestFunction1 scope
            int j = 0;
            for (j = 0; j < 20; j++)
            {
                //  j still accessible within the loop since the loop is within TestFunction1
                Console.WriteLine(j);
            }

            Console.WriteLine(j); // Ok, j still in scope (outside of loop)
        }

        public void TestFunction2()
        {
            Console.WriteLine(p);   // Ok, TestFunction2 is in the TestClass scope like TestFunction1
            //Console.WriteLine(a);   // Error, a lives in TestFunction1
            //Console.WriteLine(i);   // Error, allright now we're just getting silly ; )
        }
    }
Uncaredfor answered 7/11, 2010 at 9:26 Comment(0)
D
1

You can use an existing variable as the starting point of a for loop.

I just started learning C# 4 weeks ago, so be weary.. but the syntax is:

int x = 10;

for (x = x ; x < 15; x++) // x starts off as whatever defined above (15)
    {
        Console.WriteLine("x is: {0}", x);
    }
    // After for is done executing, x will = 15

Then for whatever reason, you can continue doing some other logic (When X < 30, something else happens) ex)

for (x = x ; x < 30; x++)
    {
        // Do stuff here
    }
Dramaturgy answered 26/8, 2013 at 0:48 Comment(0)
D
1

x=x works to re-use the variable keeping its value from one loop to another but it gives you a warning. you could prefer this syntax

for (x+=0; x>10; x++) ;
Dictatorship answered 10/7, 2018 at 12:40 Comment(0)
T
0

Another syntax to consider, if you want to use a variable from the outside, without having to re-assign or re-initialize the variable, you can omit the clause before the first semi-colon.

int c = 0;
for(; c < list1.Count; c++)
{
}

// c will start at the ending value list1.Count from the loop above
for(; c > 0; c--)
{
}
Titicaca answered 6/11, 2020 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.