I'm building a iphone app and using c++ and am having trouble checking if a pointer is null.
IMyInterface* myInterface;
if ( !myInterface ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != 0 ) { //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != NULL ){ //doesn't work
myInterfacee->doSometing();
}
if ( myInterface != ( myInterface* )0 ) { //doesn't work
myInterfacee->doSometing();
}
If myInterface is or isn't set it still enters each statement and gives me
Program received signal: “EXC_BAD_ACCESS”.
How do i go about checking if myInterface is null
Your basic problem here is that you haven't initialized myInterface
.
Assuming myInterfacee
is just a typo, the following would all be fine, and none of them would call doSometing
:
IMyInterface* myInterface = 0;
if ( myInterface ){ // ! removed
myInterface->doSometing();
}
if ( myInterface != 0 ) { // as before
myInterface->doSometing();
}
if ( myInterface != NULL ){ // as before
myInterface->doSometing();
}
if ( myInterface != ( IMyInterface* )0 ) { // IMyInterface, not myInterface
myInterface->doSometing();
}
Personally, I prefer the first two over the third, and don't like the fourth at all, but that's a question of style rather than correctness.
If myInterface is or isn't set it still enters each statement
I sort of disbelieve this, but if that's really the case (you're initializing myInterface
, and still seeing that both the if (!myInterface)
and the if (myInterface != 0)
clauses are executed), then there is something very wrong elsewhere in your program. Those tests have opposite meanings, so the only way they're both going to appear true is when something undefined is going on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With