Skip to content

Instantly share code, notes, and snippets.

@hgfernan
Created July 27, 2019 11:32
Show Gist options
  • Save hgfernan/8713a7ed87c5377b127bff73188b38a9 to your computer and use it in GitHub Desktop.
Save hgfernan/8713a7ed87c5377b127bff73188b38a9 to your computer and use it in GitHub Desktop.
Comparison of an if-else nest with a switch case statement
#include <iostream>
#include <ctime>
#include <cstdlib>
#define HALFWAY ((0 + RAND_MAX) / 2)
int main()
{
int val;
srand(time(NULL));
val = rand();
if (val == 0) {
std::cout << "val is zero" << std::endl;
} else if (val == HALFWAY) {
std::cout << "val is HALFWAY" << std::endl;
} else if (val == RAND_MAX) {
std::cout << "val is RAND_MAX" << std::endl;
} else {
std::cout << "val is " << val << std::endl;
}
switch (val)
{
case 0:
std::cout << "val is zero" << std::endl;
break;
case HALFWAY:
std::cout << "val is HALFWAY" << std::endl;
break;
case RAND_MAX:
std::cout << "val is RAND_MAX" << std::endl;
break;
default:
std::cout << "val is " << val << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment