Reyann Nassar
2 months ago
Reyanncountry asked

Why is the variable declared as int i if it was already declared as a double?

Udayan Shakya
Expert
last month
Udayan Shakya answered

Hi Reyann,

Good question. If you’re seeing both double i; and int i in the same code, here’s what’s happening:

The double i is declared outside the for loop, and the int i is declared inside the loop. In C, variables declared inside a block (like a loop) are separate from those outside — even if they have the same name.

So when you write:

double i = 3.5;

for (int i = 0; i < 5; i++) {
    // this 'i' is a different variable
}

The int i inside the loop is its own separate variable, and it temporarily hides the double i. That’s why the compiler doesn’t complain — it’s allowed, but it can be confusing.

Best practice: avoid using the same variable name in different scopes unless there’s a good reason.

If you have more questions, I am here to help.

C
This question was asked as part of the Learn C Programming course.