Multiple declarations same of variables inside and outside for loop - c

#include <stdio.h>
int main()
{
int i;
for ( i=0; i<5; i++ )
{
int i = 10;
printf ( "%d", i );
i++;
}
return 0;
}
In this variable i is declared outside the for loop and it is again declared and initialized inside for loop. How does C allows multiple declarations?

The i outside the loop and the i inside the loop are two different variables.
The outer i will live for the entire duration of main.
The inner i will only live for the duration of one loop iteration.
The inner one shadows the outer one in this scope:
{
int i = 10;
printf ( "%d", i );
i++;
}
Due to shadowing rules, it is impossible to refer to the outer one while inside the aforementioned scope.
Note that it is impossible to declare two variables with the same name in the same scope:
{
int i = 0;
int i = 1; // compile-time error
}

Variables in one scope can mask variables at a higher scope.
In this example, the i defined inside of the loop masks the i defined outside. In the loop body, the printf prints the value of the inner i, which is 10. The i++ then operates again on the inner i setting it to 11.
When the loop hits the bottom and goes back up, the inner i goes out of scope. The second and third clauses of the for then operate on the outer i. When the loop body is entered again, a new instance of the inner i is defined and initialized to 10.

You should check out the following page for the definitions of the different type of scopes that variables can have in the C language.
http://aelinik.free.fr/c/ch14.htm
Your first int i is in the scope of the entire block, and your second int i only has scope from within that nested loop. Once outside the nested loop, the original block scope version of i is applicable again.

Related

Variable hiding and "priority" in c [duplicate]

This question already has answers here:
Scope of variables in "for" loop
(2 answers)
New block scope for selection and iteration statement
(2 answers)
Closed 2 years ago.
The following program:
#include <stdio.h>
int main()
{
char i='u';
for (int i=0;i<=3;i++)
{
printf("%d\n",i);
}
return 0;
}
prints 0,1,2,3 in new lines, since the character variable i declared outside the for loop is "hid". But, the following program:
#include <stdio.h>
int main()
{
char i='u';
for (int i=0;i<=3;i++)
{
int i=8;
printf("%d\n",i);
}
return 0;
}
print 8 '4' times on new lines as if the variable i initialized as 8 has more priority than the variable i (counter) going from 0 to 3 .
The i in the for initialization and the i in the for loop are in the same block, but one seems to have more priority than the other. Does such a priority really exist and if yes, is there a defined order of priority?
What you're calling "priority" is actually referred to as scope.
Each variable and function has an enclosing scope in which the name is valid and in which it has a particular lifetime. If a variable in one scope has the same name as a variable at a higher scope, the variable(s) at the outer scope(s) is masked and only the one in the innermost scope is visible.
In the case of a variable declared in the initialization section of a for loop, these variables have a scope that is visible in the other parts of the for as well as the loop body. If the loop body is a compound statement, that starts another scope, and variables declared here will mask variables with the same name at higher scopes.
So in your second program you have three variables named i:
The scope of the first i is the body of the main function.
The scope of the second i is for statement.
The scope of the third i is the body of the for statement.
Such priority is defined by scoping rules:
The scope of any other identifier begins just after the end of its declarator and before the initializer, if any:
int x = 2; // scope of the first 'x' begins
{
int x[x]; // scope of the newly declared x begins after the declarator (x[x]).
// Within the declarator, the outer 'x' is still in scope.
// This declares a VLA array of 2 int.
}
unsigned char x = 32; // scope of the outer 'x' begins
{
unsigned char x = x;
// scope of the inner 'x' begins before the initializer (= x)
// this does not initialize the inner 'x' with the value 32,
// this initializes the inner 'x' with its own, indeterminate, value
}
unsigned long factorial(unsigned long n)
// declarator ends, 'factorial' is in scope from this point
{
return n<2 ? 1 : n*factorial(n-1); // recursive call
}

why static variable initialised in each calling of function but we have to declare it every time in C

I read that : static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. from the link.
then why I am getting error that "i was not declare " in the code given below.
I wrote program such that the static variable "i" initialized only first time when c is equal to 0 after that c increases.
I just want to know how the static variable really works and that's why i am declare static variable only once. My question is if static variable only declare once in each function call then why my code is not running and if it is necessary to declare it in each calling then why it does not initialise in each function call.
#include<stdio.h>
int c=0;
int test()
{
if(c==0)
{
static int i=0;
}
c++;
i++;
if(i==5)
printf("%d\n",i);
else
test();
}
int main()
{
test();
return 0;
}
You define the variable inside the local scope of if. It has no scope outside. static only deals with the extent (aka lifetime).
Use curly braces and indention. Then you will see your mistake.
Because the scope of i is just the if block in following code:
if(c==0)
static int i=0;
same as
if(c==0)
{
static int i=0;
}
i is not available outside the if block
If you put static variable inside of block or function then that variable will not longer available out of scope because without a curly brace {} only first statement after the if is executed. So it cannot be used anywhere else and compiler gives an error.
To fix your compilation error, declare I outside the condition. And set it to zero inside the condition -
static int i;
if ( c == 0 )
i = 0;
This will make the error go away.
But what you are trying to achieve doesn't require you to have a global variable c.
You can simply do
static int i = 0;
i++;
The first time it will be set to zero, hence forth it will not be initialized.
Its because , scope of variable 'i' is only inside (if) . So when you are incrementing 'i' , Compiler will throw error.
Adding the braces that others have mentioned will not fix the problem. The real solution is to just remove the if (c == 0) line completely. The static declaration of i should be the first line of the function.
What you want is this:
int test()
{
static int i=1;
if(i==5)
printf("%d\n",i);
else
test();
}

can an inner function use variables defined in the parent function?

Can a variable be used in an inner function if it was defined in the outer function? or should i modify the inner loop to take a third parameter which would be the array?
Example of the code i'm asking about?
perm_rec1 ( int nr_value , int N)
{
int array[];
secondFunction(int nr_value, int N)
}
The inner function:
secondFunction (int nr_value, int N)
{
int temp = array; //is This possible? Or third parameter?
}
Can a variable be used in an inner function if it was defined in the outer function?
C does not have nested functions, which is the only sense in which the "inner" and "outer" designations would make sense. When one function calls another, as in your example, it is the call that is "inside" the first function, not the called function.
In any event, variables declared at block scope, such as in your example, are visible only within the remainder of the lexical extent of the declaring block. They are not visible in the body of a function called from within that block -- not even if it is the same function, called recursively.
or should i modify the inner loop to take a third parameter which would be the array?
The most natural implementation would be, yes, to give the function a third parameter by which to provide (a pointer to the first element of) the array to that function.
There is no inner function here (nor there is in C). What you have is a function that calls another one; and no you can't access in the callee something that was defined in the caller except if you pass it explicitly as a parameter.
Interpreting what you need, you can use pointers to do that:
#include <stdio.h>
void test ( int *pointer, size_t size)
{
for (size_t i=0; i<size; i++)
{
printf("array[%zu] = %d\n", i, *pointer++);
}
}
int main(void) {
int array[] = { 1, 2, 3, 4, 5};
test(array, sizeof(array)/sizeof(array[0]));
return 0;
}
Any variable declared in the inner block shadows the outer variable declaration.
{
int a = 6;
{
int a = 9;
// won't affect the outer declaration
}
// value of a = 6 here
}
But as you are asking there cannot be any inner function in C. Only we can have inner blocks defined within braces.
Technically speaking, it is actually possible to misuse local variables to access the stack frame of a parent function, yes. But this is a very, very ugly solution, set aside platform-dependent. So just pass it as a parameter.

Accessing an outer local variable from an inner block having another variable with the same name

#include <stdio.h>
#include <conio.h>
void main()
{
int i = 1;
{
int i = 2;
printf("%d", i);
}
scanf("%d", &i);
}
I have two local variables with same name. Both have different values. The above program prints 2.
How can I access i with the value with one?
Just make a little change in your code,use integer pointer.As below:
#include <stdio.h>
#include <conio.h>
void main()
{
int i = 1;
int *p = &i; //Address of i given to p(integer pointer)
{
int i = 2;
printf("%d", i);
printf("---->Desire value in inner loop i= %d<-----\n",*p);
}
printf("---->Desire value outside of loop i= %d and *p= %d<-----\n",i,*p);
scanf("%d", &i);
}
In above code integer pointer p having address of i.So whenever u want to access inside inner loop also you can get value of i using integer pointer. Simple is that !!
C follows lexical scope. It means the name resolution of a variable is done depending on the location of the variable in the source code. The variable is resolved by searching its containing block, if that fails then searching the outer containing block.So,
{
int i=2;
printf("%d",i); //this i is the one you defined just above, inside {}
}
This next i would update the i you declared in main()
scanf("%d",&i);
which is this one,
void main()
{
int i=1;
...
So, inside the inner block {}, you cannot access the outer i, since they have the same name, and during the name resolution, the inner i will be found(as first the inner block will be searched for i).
One way is to use pointers, as pointed out by this answer below.
This all about the lexical scope here -
int i = 1;
{ // inside this you can't access the outer i as they have same name so it will be shadowed by inner one
int i = 2;
printf("%d", i); // this will print the value of inner i
}
Similarly you can't access inner i outside these { } .
If you want to print outer i you can just put a printf after the above block ends or you can make use of a pointer like this -
int i=1;
int *p;
p=&i;
and print it .
You should get acquainted with the notions:
Local variables, scope, and duration
Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

Multiple definitions for a variable

Why doesn't the following code give an error as i is defined multiple times as int i=10? Further,why isn't the iterating variable i affected? Why is there no conflict ? The output is 1010101010. How?
#include<stdio.h>
int main()
{
int i;
for(i=0;i<5;i++)
{
int i=10;
printf("%d",i);
i++;
}
}
Automatic variables are alive only in the scope {,} in which they reside.
You have two variables named i in your program:
The i declared in main has scope of entire main function.
While the i inside the for loop has scope only inside the loop.
Note that when you refer i inside the for loop the inner i shadows the i declared in the main.
int i=10; in for loop is only available inside the loop it doesn't know if it was previously defined outside the loop.
Scope of variable defined within a block of code is limited to that block only.
ie.,
int i=1;//outer i
{
int i=2;//inner i
printf("%d"&i);// this ll print 2
}
printf("%d"&i);// this ll print 1
same in for too., ie
int i=1;
for (int i=0;i<4;i++){
printf("%d",&i); // print 0 1 2 3
}
printf("%d",&i); // print 1
In your case every time you initializing inner i to 10 and printing it then you incremented inner i, so it everytime prints value of inner i you declared and initialized to 10
this is because of scope of variable
scope of variable lies within { to }
your first int i will be alive through out the main() while the int i inside for will be alive inside for loop only.
now why the output is 1010101010???
the simple explanation is when you enter for look your new i will be equal to 10, you print it then i++ makes it 11. again next time i = 10 you print it and i++ makes it 11 this continues for main() int i < 5 so five times you will get 1010101010.
hope it helps.....

Resources