Reputation: 29
i call this function like this: calculate(2)
function calculate(flag)
{
if (flag==1)
{
}
else if (flag==2)
{
}
else (flag==3)
{
}
}
In the debugger i see, that it jumps also to else (flag==3)
(apart from else if (flag==2))
.
Could someone explain it to me?
thanks H.Bada
Upvotes: -1
Views: 115
Reputation: 1
As else doesn't check any condition so from your example (flag==3) is considered as the statement enclosed in your else block i.e. the first statement after else & everything else after that statement is out of the if... else block.
So every statement thereafter will be executed regardless of the value of your variable flag.
Upvotes: 0
Reputation: 15043
Several things are going on, and you're being confused by a syntax error:
else (flag==3)
else
doesn't take a boolean condition like if
and else if
do.
See @El Ronnoco's post for the correct syntax.
Upvotes: 0
Reputation: 25571
Your code is being interpreted like this:
if (flag == 1)
{
}
else if (flag == 2)
{
}
else
{
(flag == 3)
}
You probably want another else if
statement:
else if (flag == 2)
{
}
else if (flag == 3)
{
}
Upvotes: 1
Reputation: 11922
Please post your code using the {}
code button so that it shows up nicely!
You don't want the final else (flag==3)
you either want else if (flag==3)
or just else
eg
function calculate(flag)
{
if (flag==1)
{
}
else if (flag==2)
{
}
else if (flag==3)
{
//this will execute if flag is 3
}
}
or
function calculate(flag)
{
if (flag==1)
{
}
else if (flag==2)
{
}
else
{
//this will execute if flag is not 1 or 2
}
}
Upvotes: 6