Sign in to follow this  
Followers 0
Taggsladder

Coding question, function pointer, check if null.

4 posts in this topic

Hello

I don't know if this is quite the right place to post this or if my title is describing this correct and maybe this is more of a general C questions, but I hope its OK to post it here. It is on a MSP430 Launchpad anyway.

The code is simplified, there is more parameters passed to the function etc.

// I have a function like this.
void foo (char* bar) {
  
  if (!bar) Serial.print("bar is NULL"); // I want to check when NULL is passed on but this doesn't work?
  // Also tried (bar == NULL) and (bar[0] == NULL)...
  else Serial.print("bar is not NULL");
}

// Usually I call it like this.
foo("Normally text passed here");

// But I would like to call it like this also.
foo(NULL);

Looking forward to any reply.

Best regards

Share this post


Link to post
Share on other sites

"if (bar[0]==NULL)" won't look at the pointer value, but instead the memory the pointer references, so that is right out, unless you want to know if the parameter is an empty string (only the null terminator)

"if (bar == NULL)" should work, in particular if you explicitly pass NULL in since you are comparing a value to itself, as should "if (!bar)", since NULL should be 0.

I just checked both (using gcc on a windoze machine) and they work as expected, so I can offer no insight as to why you would have a problem. I would suspect that you are seeing a symptom of some other issue than pointer comparison.

Fmilburn, Taggsladder and energia like this

Share this post


Link to post
Share on other sites
22 hours ago, enl said:

"if (bar[0]==NULL)" won't look at the pointer value, but instead the memory the pointer references, so that is right out, unless you want to know if the parameter is an empty string (only the null terminator)

"if (bar == NULL)" should work, in particular if you explicitly pass NULL in since you are comparing a value to itself, as should "if (!bar)", since NULL should be 0.

I just checked both (using gcc on a windoze machine) and they work as expected, so I can offer no insight as to why you would have a problem. I would suspect that you are seeing a symptom of some other issue than pointer comparison.

 

Thank you for your input. I think you are right, I looked at some other of my projects and found that I use similar code there that works. I need to dig into it :)

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0