Simple problem

It's simple, I know, but I can't figure it out.

#include "stdafx.h"
#include <iostream>

using namespace std;

int x = 0;

void loopMethodTest()
{
cin.get();
}

int main()
{
while(x = 0)
{
loopMethodTest();
}
}

I want to know WHY this immediately exits upon start up. I set x equal to 0, but when the program reaches main, it ignores the fact that x equals 0 and skips over the while loop that will call the method looptest() while x equals 0.

Thanks for reading!

-Braddertt
Last edited on
[code] "Please use code tags" [/code]
= assignment
== comparison
Well, you have a single = there, which is assignment, not equality checking. Change it to an "==" and it will work.
You need to use 2 equal signs. For people starting C++, a common recommendation is to write the comparisons with the literal value to the left. If you do this, then the compiler will catch your error:

1
2
3
4
5
6
7
8
9
10
11
12
whle (0 == x)  //Correct way.
{
    loopMethodTest();
}

....

while (0 = x) //Incorrect, but the advantage is that the compiler will tell you.
{

    loopMethodTest();
}
Thank you very much. Silly me.
On another note, to further clarify the behavior, look at the following two lines:
1
2
3
4
5
x = 1; //returns the value of 1
x = 0; //returns the value of 0
while(x = 0) //assignment returns the value of 0, 0 is interpreted as false, skips loop
{ //stuff
}
Topic archived. No new replies allowed.