a beginner's problem

Hello everyone, I'm new to the forum, to C++ and to programming in general.
I'm having a little problem with setting booleans to "true" or "false" as I please.
I was trying to write some pretty basic code, using "while" loops and booleans, when I noticed I had no control over the state of the booleans I created.
So I wrote the simplest code I could think of to test how booleans work.


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std; 
int main () 
 {
  bool k;
  k = false;
  if (k = true)
  cout << "k is true";
  else
  cout << "k is false";
  return 0;
 }


It seems pretty straightforward right?
And yet, the string shown is always "k is true"!
I think I'm missing something about the way booleans are supposed to be used...
the = operator is for assignment, the == operator is for comparison

in your code if (k = true) should be if (k == true)
if(k = true)

You are using the assignment operator here, so you are making k=true (which is why it always thinks it's true)

You want to do the comparison operator instead:

if(k == true)

Or, since k is already a boolean, you don't really even need to compare it to anything:

if(k) // is the same as if(k == true)


EDIT: doh, too slow

EDIT 2: lol firedraco
Last edited on
You need to use == in the if statement. = is assignment, == is comparison.

Also, you don't have to compare bools like that:

if(k) { //same as if(k == true)

EDIT: Dammit guys!
Last edited on
what a fast and useful reply! thanks everyone! I like this forum already!
Topic archived. No new replies allowed.