Skip to content

Instantly share code, notes, and snippets.

@teeks99
Last active August 29, 2015 14:17
Show Gist options
  • Save teeks99/8f056f64ff81e4a9c6f9 to your computer and use it in GitHub Desktop.
Save teeks99/8f056f64ff81e4a9c6f9 to your computer and use it in GitHub Desktop.
C/C++ Boolean Order of Operations
#include <iostream>
using namespace std;
std::string boolStr(bool value)
{
if(value)
{
return "true";
}
return "false";
}
void printResults(bool tryEmpty, bool tryFirst, bool trySecond)
{
std::cout << "Empty: " << boolStr(tryEmpty) << " ";
std::cout << "FirstSet: " << boolStr(tryFirst) << " ";
std::cout << "SecondSet: " << boolStr(trySecond) << std::endl;
}
int main()
{
cout << "Boolean order of operations" << endl;
bool tryEmpty, tryFirst, trySecond;
std::cout << "true && true || false, always passes" << std::endl;
printResults(
true && true || false,
(true && true) || false,
true && (true || false)
);
std::cout << "true && false || true" << std::endl;
printResults(
true && false || true,
(true && false) || true,
true && (false || true)
);
std::cout << "false && false || true" << std::endl;
printResults(
false && false || true,
(false && false) || true,
false && (false || true)
);
std::cout << "false && true || false, always fails" << std::endl;
printResults(
false && true || false,
(false && true) || false,
false && (true || false)
);
return 0;
}
/* Output
Boolean order of operations
true && true || false, always passes
Empty: true FirstSet: true SecondSet: true
true && false || true
Empty: true FirstSet: true SecondSet: true
false && false || true
Empty: true FirstSet: true SecondSet: false
false && true || false, always fails
Empty: false FirstSet: false SecondSet: false
*/
// ----- Result -----
// a && b || c == (a && b) || c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment