Skip to content

Instantly share code, notes, and snippets.

@illescasDaniel
Created December 26, 2016 14:39
Show Gist options
  • Save illescasDaniel/62367e4f10832cb8aed85177acd4277f to your computer and use it in GitHub Desktop.
Save illescasDaniel/62367e4f10832cb8aed85177acd4277f to your computer and use it in GitHub Desktop.
Guard statement from Swift in C++
#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