Skip to content

Instantly share code, notes, and snippets.

@maddouri
Last active August 20, 2019 21:32
Show Gist options
  • Save maddouri/c8ab299b592ede4e5b473963a91e7720 to your computer and use it in GitHub Desktop.
Save maddouri/c8ab299b592ede4e5b473963a91e7720 to your computer and use it in GitHub Desktop.
Dereference a pointer only if it is not null
#pragma once
// Dereference a pointer only if it is not null
#define ifnotnull(p) for (auto* p__ = p; p__ != nullptr; p__ = nullptr) (*p__)
// 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