Skip to content

Instantly share code, notes, and snippets.

@mshafae
Created October 8, 2024 19:17
Show Gist options
  • Save mshafae/0a21e4c9277838ed0c57e3e9b9ecd5a3 to your computer and use it in GitHub Desktop.
Save mshafae/0a21e4c9277838ed0c57e3e9b9ecd5a3 to your computer and use it in GitHub Desktop.
Common mistakes with if, else-if, and else
// Gist https://gist.github.com/mshafae/0a21e4c9277838ed0c57e3e9b9ecd5a3
// Filename cpsc120_common_if_mistakes.cc
// CompileCommand clang++ -std=c++17 cpsc120_common_if_mistakes.cc
// Common mistakes with if, else-if, and else
// -- Start -- Turns off warnings - do not do this at home
#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#pragma clang diagnostic ignored "-Wempty-body"
#pragma clang diagnostic ignored "-Wparentheses"
// -- End -- Turns off warnings - do not do this at home
#include <iostream>
#include <string>
int main(int argc, char const *argv[]) {
int number{42};
// The assignment operator (=) always is 'true'
// The common mistake is to accidentally use = instead of == or !=.
if (number = 17) {
std::cout << "number should be 42 when it is really " << number << ".\n";
} else {
std::cout << "number should be 42 when it is really " << number << ".\n";
}
// We have a habit of putting semicolons at the end of everything. With
// if statements it will cause the if statement to abort and not execute
// the body of the condition.
if (number == 99); {
std::cout << "number is " << number << " but it appears to be 99.\n";
}
// If you try to put an else here it won't compile because of the semicolon.
// If you want to do a range
if (33 < number < 47) {
std::cout << "number is " << number
<< " and it passes the test 33 < number < 47.\n";
} else if (number == 17) {
std::cout << "number is " << number
<< " and it passes the test number == 17.\n";
} else {
std::cout << "number is " << number
<< " and it failed the test 33 < number < 47 and the test number "
"== 17.\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment