Created
December 26, 2016 14:39
-
-
Save illescasDaniel/62367e4f10832cb8aed85177acd4277f to your computer and use it in GitHub Desktop.
Guard statement from Swift in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#define guard(_condition) if (bool(_condition)){} | |
using namespace std; | |
// Example inside a function | |
template <typename Type> | |
Type biggestNumber(Type* numbers, const size_t& size) { | |
guard(numbers != nullptr) else { | |
cerr << "[Error, null pointer found] "; | |
return Type{}; | |
} | |
Type biggest = 0; | |
for (size_t i = 0; i < size; ++i) { | |
if (numbers[i] > biggest) { | |
biggest = numbers[i]; | |
} | |
} | |
return biggest; | |
} | |
int main() { | |
boolalpha(cout); | |
int* i = new int{10}; // nullptr; | |
guard(i != nullptr) else { | |
cerr << "Null pointer" << endl; | |
exit(1); | |
} | |
guard(*i == 10) else { cerr << "Incorrect value" << endl; } | |
delete i; | |
// | |
double* numbers = nullptr; //new double[4]{1.1, 2.3, 9.01, 9.0}; | |
cout << "Biggest number: " << biggestNumber(numbers, 4) << endl; | |
delete[] numbers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment