Multiple definitions for a variable - c

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.....

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
}

Multiple declarations same of variables inside and outside for loop

#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.

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.

What will be the output of this?

I was doing this question and I have a doubt.
#include <stdio.h>
int main(void)
{
int fun (int);
int i=3;
fun(i=fun(fun(i)));
printf("%d\n",i);
return 0;
}
int fun ( int i )
{
i++;
return(i);
}
I have a doubt when it gets to
fun ( i = 5 )
What happens with this? Will the value of i go to 6 or it will be 5.
According to me, it should be 6. But that is not the correct answer.
In C, parameters are passed by value. The variable i in the main function is actually different from the i inside fun(), because its value is copied when it is passed into the function.
When you call i = fun(fun(i)), 5 is isassigned into i in the main function. However, the call to fun(5) that returns 6 does not assign its result back into i, leaving it unchanged. When the output is printed, i is still 5.
This is related to scope. In the function scope, variables defined in that scope or the parameters pass in does not any effect on outer scope variables, unless it is a pointer. So, the output of fun will be assigned to i in the fun(i = 5) but the internal operations of fun, do not effect the outer scope i. So it stays as it is before fun last call. The output is 5.
The result of the call to fun() is not assigned to i. Therefore 5 is expected, not 6.

Heap and Stack segment

I came across a small puzzle for which I was trying to find the output. Once I managed to get the output, I tweaked in 1 line and the output is totally different. Why does the output of the following two programs vary?:
a)
#include<stdio.h>
int fun()
{
static int num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
Output:
38 35 32 29 26 23 20 17 14 11 8 5 2
b)
#include<stdio.h>
int fun()
{
static int num;
num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
Output: Infinite loop printing 40 everytime
There is just one difference: The declaration and initialization are done at the same time in (a) but separately in (b). How does that effect the final outcome?
static int num = 40;
static int num;
These both get evaluated once. num does not live on the runtime stack (but rather in the data segment) Then,
num = 40;
gets evaluated every time you call fun(). You're reassigning a variable that was declared outside the stack to 40, causing it to loop forever.
In the first one, num will only be initialised to 40 the first time the function is called. In the second one, it is set to 40 every time the function is called.
first one, num gets initialized once, no matter how many times you call the function
second one, num gets set to 40 every time you call the function
Two concepts need to be looked into here
lifetime of variable
scope of variable
The lifetime of a variable is the period over which it exists. If num were defined without the keyword static, the lifetime would be from the entry into fun() to the return from fun(); so it would be re-initialized to 40 on every call.
The scope of variable is where the variable name can be seen. Here, num is visible only inside function fun().
The keyword static is used to extend the lifetime of a variable to the lifetime of the program. In case of static declaration initialization occurs only once and then the variable retains its value inside the routine fun(). So if you are overwriting it by setting it to value of 40 in the second case its values keeps getting set to 40 on every call to fun(). The declaration of the variable num as static is redundant in your second code.

Resources