KastelA Kastel
KastelA Kastel

Reputation: 83

If statement in if statements

I'm trying to understand the logic behind this code

int i = 13;
if (i<10) if (i>=5)   Console.WriteLine("Case number 1");
else Console.WriteLine("case number 2");
Console.ReadLine();

So I know this isn't proper code (since there should be brackets to make this app works).

I know how to make this code "clean" by modifying it

But I'm trying to understand how Csharp is actually behaving with this erronated code, the logic behind the execution of this code

From what I read, the else applies to the closest if, in this case (if >= 5).

So when I write i = 3 it reads the first if and goes to the first else and console gives me "Case nr 2".

When I write i = 7 it reads the 2nd and gives me "Case nr 1"

when I write i = 13 it gives me nothing

From what I understood while researching it should go the else since 2 if's have been tested before, so from what I understand when it tests the first if it should go to the else, if it tests both if's it should go to the 2nd too since the if's don't really make sense.

If it only tests the 2nd if it should give me case number.

So I'm definitely wrong in my way of thinking, but I can't find why it doesn't show up anything

Upvotes: 0

Views: 95

Answers (2)

Hamid Pourjam
Hamid Pourjam

Reputation: 20764

Your code is like this:

if (i < 10)
{
    if (i >= 5) {
        Console.WriteLine("Case number 1");
    }
    else {
        Console.WriteLine("case number 2");
    }
}

Console.ReadLine();

so if i is in [5,10) it is case number 1 and if it is in (-Infinity,10) it is case number 2

Some hints:

  • consider using some well known code conventions
  • use indentations to make the code more readable
  • use opening and closing curly braces whether you have a block with one statement or multiple statement
  • try not to have some magic text in your code, here "Case" and "case" is something that can cause later issues for you mainly in test scenarios

Upvotes: 2

SMA
SMA

Reputation: 37093

This is how your if loop works (i indended your code and added braces):

int i = 13;
if (i<10) {
    if (i>=5) {  
        Console.WriteLine("Case number 1");
    } else {
        Console.WriteLine("case number 2");
}
Console.ReadLine();

So inner else corresponds to if with condition i >= 5 Hence when your i = 13, it behaves like:

 is i < 10? No

And hence never enter's if and executes next statement i.e. Console.ReadLine();

Upvotes: 5

Related Questions