'How do i write nested if statement? [closed]
So i want to make a simple if statement like this :
if(a=1)
{
if(variable1=1)
{
cout<<"a1=1";
}
else
{
cout<<"error";
}
}
if(a=2)
{
if(variable1=1)
{
cout<<"a2=1"
}
else
{
cout<<"error";
}
}
Problem : When i set a to 2 and variable1 to 1 it will just print a1=1 not a2=1. How do i fix this? Sorry if there is a miss-writing, or bad english in this post. I hope someone answers...
Solution 1:[1]
You are using the assignment operator(=) instead of the comparison operator (==). The assignment operator will always return true if the assignment is successful, hence it is going in the first if statement.
To solve the issue, change = to == in your code.
if (a == 1){
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepak Patankar |
