nomorequestions
nomorequestions

Reputation: 589

Working of C code when same variable is defined with different data type

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

Answers (4)

Leonardo Bernardini
Leonardo Bernardini

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

Mike Dinescu
Mike Dinescu

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:

  • blocks inherit all global variables
  • variables declared inside a block are only valid inside the block
  • blocks can be nested
  • a nested block inherits the variables from the outer block,
  • variables may be declared in a nested block to hide variables in the outer block (such as in your case)

EDIT

As @pmg suggested, here are a couple of extra points:

  • a hidden variable cannot be accessed at all, except through use of pointers created when it was still visible
  • although strictly speaking, hiding variables is not an error, it's almost never a good thing and most compilers will issue warnings when a variable is hidden!

Upvotes: 3

BLUEPIXY
BLUEPIXY

Reputation: 40145

while(t>0)//int t;
{
    {
        double t;
        scanf("%lf",&t);
        printf("%lf\n",t);
    }
    t--;
}

Upvotes: 1

jhauris
jhauris

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

Related Questions