Last active
August 20, 2019 21:32
-
-
Save maddouri/c8ab299b592ede4e5b473963a91e7720 to your computer and use it in GitHub Desktop.
Dereference a pointer only if it is not null
This file contains 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
#pragma once | |
// Dereference a pointer only if it is not null | |
#define ifnotnull(p) for (auto* p__ = p; p__ != nullptr; p__ = nullptr) (*p__) |
This file contains 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
// Try Online: http://coliru.stacked-crooked.com/a/df2a5066990e150f | |
#include <iostream> | |
// Dereference a pointer only if it is not null | |
#define ifnotnull(p) for (auto* p__ = p; p__ != nullptr; p__ = nullptr) (*p__) | |
struct Foo | |
{ | |
void bar() const { std::cout << "hello\n"; } | |
}; | |
int main() | |
{ | |
Foo foo; | |
ifnotnull(&foo).bar(); // Prints "hello" | |
ifnotnull(static_cast<Foo*>(nullptr)).bar(); // Doesn't do anything | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment