Code Meaning: (char *)-1

  • Thread starter karthigan.srinivasan
  • Start date
K

karthigan.srinivasan

What does (char *)-1 mean? I see it used often in an if statement condition? Please explain.

Best Regards,
Karthigan.
 
G

Guest

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 NULLto indicate an invalid value.
 
K

Kaz Kylheku

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.

Negative one to pointer is common on Unix in the following situation:

if (mmap(...) == (void *) -1) {
/* mmap failed; errno has error */
}
 
K

Keith Thompson

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.

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.

Probably the code that uses it operates in an environment where there
are additional guarantees, or the author just isn't worried about the
(very small) risk.
 
K

Keith Thompson

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.

And it's also possible that (char*)-1 is a trap representation.
 
G

gwowen

Negative one to pointer is common on Unix in the following situation:

  if (mmap(...) == (void *) -1) {
    /* mmap failed; errno has error */
  }

Correct. The most modern POSIX says that mmap() returns MAP_FAILED on
failure, but for backwards compatibility reasons MAP_FAILED is almost
always (char*)-1 [which is then implicitly converted to (void*), since
(void*)-1 is non-standard.]
 

Ask a Question

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.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top