Reputation: 589
I unknowingly named a variable twice but with different data type. It missed the compilation error as one is in main()
and other is in while()
loop of main()
.
So I made a code like this.
#include <stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t>0)
{
double t;
scanf("%lf",&t);
printf("%lf\n",t);
t--;
}
return 0;
}
And here I notice that the program never ends! For any input value of double t
either a negative or positive or zero, while()
loop never gets terminated.
Can anyone care to explain why is this happening? How does the while loop get terminated there?
Upvotes: 2
Views: 85
Reputation: 1116
When the statement t--
is executed, it refers to the (double t
) variable declared earlier in the same block, so your int t
in the outer block scope, which is shadowed by the double t
, never gets decremented.
Upvotes: 0
Reputation: 55720
You said it yourself. You have two variables named t
with different scope.
The double t
you declared has the scope of the block that executes inside of the while loop. The conditional in the while loop uses the t
that is declared in the scope surrounding the while loop (the int t
) which is never modified (because the loop hides t
and modifies the double t) and so it never reaches 0.
Here are some points about scope of variables in C:
EDIT
As @pmg suggested, here are a couple of extra points:
Upvotes: 3
Reputation: 40145
while(t>0)//int t;
{
{
double t;
scanf("%lf",&t);
printf("%lf\n",t);
}
t--;
}
Upvotes: 1
Reputation: 1143
Can anyone care to explain why is this happening?
There are two variables in your program called t. One is an int
, at the scope of main, and one is a double
, in the scope of the while loop. Inside the while loop the double t is hiding the int t, and your scanf is setting the double t.
How does the while loop get terminated there?
The program can't be terminated from inside the while loop as written.
Upvotes: 1