Equal variables within different functions

Hello people. I would like to know if the following is correct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

int function_1 (*Parameters*)
{
int i;

*** CODE ***

}

int function_2 (*Parameters*)
{
int i;

*** CODE ***

}

int main ()
{
*** CODE ***
}


This is, if I declare some variable
int i
within a function, can I use the same identifier to declare other variables within other functions?

Thank you for your help!
Sorry, I forgott something: can I use that same identifier within the main function?
Yes, you can. You even can write this:
1
2
3
4
5
6
7
8
9
10
11
void f1(){
           int i;

           //do something

           while(true){
                      int i;
                      // do something else

           }
}

The only thing you should know tat all these variables declared in different blocks are independent.
Yes, this is called the scope of the variable and is limited by the block within which it's declared. Blocks are delimited by braces { } and/or function/method definitions. If something is declared within a block, that's called local scope, and outside of any block is global scope.

As you suspected, this means that if a variable is declared with the same name in more than one block, all instances of that variable are separate.

Also keep in mind that local scope has priority over global scope, and nested blocks have priority over outer blocks.

So, with reference to tfityo's example

1. Within the while loop, referencing i will use the int i declared at line 7, not the one at line 2 (the while loop is a nested block).

2. Outside of the while loop, and within function f1(), the int i declared at line 7 is out of scope (not defined), so the one from line 2 is used.

3. Outside of the f1() function, i is undeclared.

Cheers
Jim
Topic archived. No new replies allowed.