Printf %d and %ld

This is a discussion on Printf %d and %ld within the C Programming forums, part of the General Programming Boards category; Hello everyone, I think printf %d works fine with signed, unsigned and negative integer values, and the same as %ld ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    Printf %d and %ld

    Hello everyone,


    I think printf %d works fine with signed, unsigned and negative integer values, and the same as %ld for long. Is that correct? If not, do we need to special conversion?


    thanks in advance,
    George

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    %d works for "normal length integer", whilst "%ld" is for "long" integers. Unsigned numbers should use "%u" or "%lu" depending on length. If you print a "large" unsigned with %d, then the result will be a negative number - which isn't what the unsigned number should be, since by definition, unsigned numbers are always positive. [Or, rather, they don't have a sign, if you want to represent only negative numbers, you could put a minus there yourself, but it's not got a "positive/negative" representation].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    %d works for "normal length integer", whilst "%ld" is for "long" integers.
    Where a normal integer is an int, and a long integer is a long int.

    To answer your question, you're supposed to use %d for signed (or ordinary) ints, and %u for unsigned ints; %* for normal ints, and %l* for long ints.

    If you don't specify a signed-ness, signed is the default. And if you don't say "long", then a normal sized int results.

    These are all signed (%d):
    Code:
    int x;
    signed int x;
    123;
    These are unsigned (%u):
    Code:
    unsigned x;
    unsigned int x;
    123u;
    These are long (%ld):
    Code:
    long x;
    long int x;
    123l;
    123L;
    These are unsigned long (%lu):
    Code:
    unsigned long x;
    unsigned long int x;
    123ul;
    123UL;
    123Lu;
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21