Jump to content
43oh

Coding question, function pointer, check if null.


Recommended Posts

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

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.

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 :)

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...