Click here to Skip to main content
14,733,548 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am trying to really understand the core of c# programming. I am in process of still learning the fundamentals.

And I do not understand why I can not set a variable in the loop. Why is that? It makes perfect sense to do that, but it is not allowed. Why?

I did that:

int c = 0;
            
            for (int x = 1; x < 21; x++)
            {
                int c += x;

            }
            Console.WriteLine(c);
            Console.ReadKey();


And It takes me so long to figure out, that I must remove the "int" before "c". But do not understand why.

What I have tried:

int c = 0;
            
            for (int x = 1; x < 21; x++)
            {
                c += x;

            }
            Console.WriteLine(c);
            Console.ReadKey();


That works.
Posted
Updated 13-May-20 17:09pm

This comes down to what is known as scope, and there are varying levels of it.

In your first sample; you are effectively declaring a new variable which is local to that block of code (the for loop). Once that block ends, so does that variable.
for (int x = 1; x < 21; x++)
{
      int c += x;
}
In your other sample; you are not defining that variable within the FOR block; but it is declared within the same method as the for loop so it is accessible within the loop
int c = 0;
for (int x = 1; x < 21; x++)
{
    c += x;
}

In a nutshell... if it's created within a block, it is not accessible after the block ends
   
v2
Quote:
And I do not understand why I can not set a variable in the loop. Why is that? It makes perfect sense to do that, but it is not allowed. Why?

You need to learn about scope of variables.
A variable defined inside a pair of {} exist only inside them.
Scope of Variables in C++ - GeeksforGeeks[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900