Click here to Skip to main content
15,904,153 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
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

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.
 
Share this answer
 
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.
 
Share this answer
 
Your output has to be "I am a boy."
 
Share this answer
 
v2
Your understanding is correct and strOutput must be "I am a boy.".

-Saurabh
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900