Not operator trouble

So whenever I try to run this, it only executes the code in the if statement when a == b, which is the opposite of what I wrote. I've tried initializing a to 7, and even adding a statement to make a and b equal before the if statement. I also tried changing the != to < or >, but those just make the condition execute every time. I feel like I'm missing something really obvious and I'm going to kick myself when I find out what it is. I'm using Code::Blocks on an old HP Pavilion laptop running Windows 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;

int main()
{
int a;
int b = 7;
cin >> a;
if (a != b);
{
    cout << "nope";
    cin >> a;
}
    return 0;
}
Last edited on
You need to remove the semicolon after your if statement, then it will work.
What you've written is the equivalent of:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;

int main()
{
int a;
int b = 7;
cin >> a;
if (a != b)
{
    ;
}

{
    cout << "nope";
    cin >> a;
}
    return 0;
}


I hope that makes it clearer why that semicolon shouldn't be there.

EDIT: Also, I strongly recommend you adopt a consistent indentation style. It will make it much easier for you - and us - to see the flow of control and logic in your code, and make it easier to spot errors.
Last edited on
I knew it was something obvious, lol. Thanks so much guys!
You're welcome - glad it worked!
Topic archived. No new replies allowed.