Sunday, 25 August 2013

Why can't we use “%d” in C language instead of “%u” with pointers?

  • %d will show a negative value for addresses with the most significant bit set (high addresses)
  • %u will always show the positive interpretation of the bits
  • %p is the best, since it's explicitly reserved for printing addresses.
Consider this, supposing an address of 0xffffffff.
#include <stdio.h>

int main () {
    void* val = 0xffffffff;

    printf("d = %d\n", val);
    printf("u = %u\n", val);
    printf("p = %p\n", val);

    return 0;
}
And, it's output:
d = -1
u = 4294967295
p = 0xffffffff

No comments:

Post a Comment