15,881,413 members
See more:
I'm no expert, but I honestly thought I understood `if` and `else` OK... but I'm not sure now :~

So, just to make absolutely sure, if you have

```int a = 0;
int b = 1;
CString strOutput;
if(a == 0)
{
strOutput = "I am a boy.";
}
else if(b == 1)
{
strOutput = "I am a girl.";
}```

what does `strOutput` say?

I thought it'd be "I am a boy.", but I was debugging through some code when it said "I am a boy." then "I am a girl.", i.e. executed both branches.

Admittedly, I was making a mess of memory access all over the place, so it could have been that, but please, some one tell me, should this piece of code execute all paths, or just one? And have I got the number of brackets right? (The compiler should have spotted that, of course, but hey...)

As an aside, part of the confusion is that my preferred tool that is Matlab distinguishes between `if`-`else` and `if`-`elseif`.
Posted

## Solution 1

Your understanding is correct and strOutput must be "I am a boy.".

-Saurabh

v2

## Solution 2

Your output has to be `"I am a boy."`

v2

## Solution 3

Your `if` - `else` understanding is correct and also the number of `{}` brackets.
PaulowniaK wrote:
```if(a == 0)
{
strOutput = "I am a boy.";
}
else if(b == 1)
{
strOutput = "I am a girl.";
}```

The 2nd pair of `{}` brackets belong to the `if`, you could also write:
```if(a == 0)
{
strOutput = "I am a boy.";
}
else
{
if(b == 1)
{
strOutput = "I am a girl.";
}
}```

But the result will be the same.

## Solution 4

Hi PaulowniaK,

There is no difference & your code is absolutely right. It must print out "I am a boy" only and not the second part as it already entered into the if {} block.

Are you noticing the same again and again, means are you able to reproduce it any time? Let me know.