C++ Booleans and flow control,

Spread the love

C++ Booleans are a byte sized memory space which simply holds the data variable for ” is it true or is it not?”. Programmers usually put the word “is” in front of the variable so that it reads more English like. So a bool is likely to be named isbeautiful or isCorrect, rather than simply beautiful which could be an int rating from 1 – 10.

Adding the “is” to a variable such as “cold” does not make it a bool. It must be specifically declared as a bool.

Usually c++ booleans are used as part of flow control. Flow control is usually handled by either select case statements or if then else or just a plain if statement. But while(true) and do { blah blah} while (true) are also sometimes used.


/*
    C++ datatype bool, known as boolean. 
    Takes up 1 Byte of space.
    Programmer: Jane the famous Doe
    Date: May 2020
    Cause: Sample code showing booleans and 
           how they are used in flow control
*/

#include <iostream>
  
using namespace std;
  
int main(){
  bool isTrue  = true;
  bool isFalse = false;
  if ( isTrue )
    cout << "Yes, 1 is True " << isTrue << endl;
  if ( isFalse ) 
    cout << "0 is really false, see : " << isFalse;
}
/* So, what is wrong with this code
   other than the fact that isFalse will never
*/ show us its true colors


The above code compiles and works.

The bool variable can be either a one or zero.

Zero is always false. Anything else is true. That’s the convention.

Use your compiler or click here to fix the problem and enable both isTrue and isFalse to both show their cout << lines

Answer below, but try doing it on your own.


#include <iostream>
  
using namespace std;
  
int main(){
  bool isTrue  = true;
  bool isFalse = false;
  if ( isTrue )
    cout << "Yes, 1 is True " << isTrue << endl;
  if ( !isFalse ) 
    cout << "0 is really false, see : " << isFalse;
}



These code blocks aren’t very large yet.

Remember the best learning comes from

  • memorizing the code
  • replaying it in your head
  • writing it into the http://cpp.sh window from memory
  • Teaching someone else


-> Lesson 6 C++ Switch, Flow Control

Top