Tech Support Guy banner
Status
Not open for further replies.
1 - 3 of 3 Posts

·
Registered
Joined
·
126 Posts
Discussion Starter · #1 ·
When I compile my program, the IF statements fail to work correctly. I ask the user to input my newly defined int variable, and have the IF statements run off of whatever they put in, but no matter what they enter, it starts up on the first IF statement.

int choice;
cin>>choice;
if (choice = 1)
cout<<"Addition-";
cout<<"Enter first number: ";
int first;
cin>>first;
cout<<"Enter second number: ";
int second;
cin>>second;
cout<<first + second;
goto start;
if (choice = 2)
cout<<"Subtraction-";
cout<<"Enter first number: ";
int first1;
cin>>first1;
cout<<"Enter second number: ";
int second1;
cin>>second1;
cout<<first1 - second1;
goto start;
if (choice = 3)
cout<<"Multiplication-";
cout<<"Enter first number: ";
int first2;
cin>>first2;
cout<<"Enter second number: ";
int second2;
cin>>second2;
cout<<first2 * second2;
goto start;
if (choice = 4)
cout<<"Division-";
cout<<"Enter first number: ";
int first3;
cin>>first3;
cout<<"Enter second number: ";
int second3;
cin>>second3;
cout<<first3 / second3;
goto start;
}
 

·
Registered
Joined
·
260 Posts
Just thought I would add that a good coding habit to get into that will help new coders (and advanced one too :p) locate this common error easily is to put the constant as the first element in the check. If you do this the error will be produced at compile time and is much easier to remedy.

ie:
Code:
// do it like this
if(1 == choice)
{
...
}
// rather than like this
if(choice == 1)
{
...
}
if you leave out an = sign in the first if statement, you will get a compile time error because you cannot assing a value to a constant, but if you do it the second way, the program will run, but it will behave strangely and unexpectedly.

Cheers
 
1 - 3 of 3 Posts
Status
Not open for further replies.
Top