K
karthigan.srinivasan
What does (char *)-1 mean? I see it used often in an if statement condition? Please explain.
Best Regards,
Karthigan.
Best Regards,
Karthigan.
What does (char *)-1 mean? I see it used often in an if statement condition? Please explain.
It casts (converts) -1 into a ptr-to-char. It's highly likely that this isn't
a valid value for a pointer. My guess is someone is trying to indicate they
don't have a valid char* or string available. This is *not* a commonly used
idiom (way of writing code). It looks pretty silly to me. I'd use NULL to
indicate an invalid value.
Paul N said:Possibly the programmer wants to distinguish between two types of
failure, and so is using NULL (or 0, which is the same) for one type,
and (char *)-1 for the other type, as well as returning a string if
the function works.
Keith Thompson said:It's potentially non-portable, though in practice it shouldn't be a
problem. It's at least theoretically possible that (char*)-1 == NULL.
It's also conceivable, but quite unlikely, that (char*)-1 has the same
value as some valid pointer.
Negative one to pointer is common on Unix in the following situation:
if (mmap(...) == (void *) -1) {
/* mmap failed; errno has error */
}
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.