Thread: format specifier of size_t

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    87

    format specifier of size_t

    I have heard that c99 has the format specifier %zu for this and in C 89 % lu was used. What about scanning size_t variables ?

    eg.
    Code:
      size_t a;
    
      scanf("%lu", &a);
    Is this okay or a cast is required here as well ?

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Is this okay or a cast is required here as well ?
    I don't think you can read directly into a size_t variable in C89. I think you would need to first read into some other type variable, for example an unsigned long, long, or long long, then assign this to a size_t.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    It is possible to work out what a size_t actually is. Methods include;

    1) Compare sizeof(size_t) with sizeof(unsigned short), sizeof(unsigned long), or [C99 only] sizeof(unsigned long long). Whichever one matches is the actual type of a size_t for your implementation.

    2) [C99 only] Look at SIZE_MAX (from <stdint.h>) and compare with USHRT_MAX, ULONG_MAX, and ULLONG_MAX (the maximum values representable respectively in unsigned short, unsigned long, and unsigned long long respectively, from <limits.h>.

    If there is no match with these methods, then that would mean size_t is a different type from any unsigned integral type supported by your compiler. In practice, I've yet to encounter any compiler that will not yield a match but, strictly speaking, it could occur.

    Note: C89 and C++ do not support long long integral types (although some compilers do).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 03:49 PM
  2. Format Specifier
    By babu in forum C Programming
    Replies: 2
    Last Post: 06-27-2007, 11:17 PM
  3. system command not executing with format specifier
    By ridhamshah in forum C Programming
    Replies: 6
    Last Post: 11-08-2006, 05:58 AM
  4. string format specifier
    By Bleech in forum C Programming
    Replies: 4
    Last Post: 07-31-2006, 04:43 PM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM