Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - difference between stdint.h and inttypes.h

What is the difference between stdint.h and inttypes.h?

If none of them is used, uint64_t is not recognized but with either of them it is a defined type.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

stdint.h

Including this file is the "minimum requirement" if you want to work with the specified-width integer types of C99 (i.e. int32_t, uint16_t etc.). If you include this file, you will get the definitions of these types, so that you will be able to use these types in declarations of variables and functions and do operations with these datatypes.

inttypes.h

If you include this file, you will get everything that stdint.h provides (because inttypes.h includes stdint.h), but you will also get facilities for doing printf and scanf (and fprintf, fscanf, and so on.) with these types in a portable way. For example, you will get the PRIu64 macro so that you can printf a uint64_t like this:

#include <stdio.h>
#include <inttypes.h>
int main (int argc, char *argv[]) {

    // Only requires stdint.h to compile:
    uint64_t myvar = UINT64_C(0) - UINT64_C(1);

    // Requires inttypes.h to compile:
    printf("myvar=%" PRIu64 "
", myvar);  
}

One reason you would want to use printf with inttypes.h is, for example, that uint64_t is long unsigned in Linux but long long unsigned in Windows. Thus, if you were to only include stdint.h (not inttypes.h), then, to write the above code and keep it cross-compatible between Linux and Windows, you would have to do the following (notice the ugly #ifdef):

#include <stdio.h>
#include <stdint.h>
int main (int argc, char *argv[]) {

    // Only requires stdint.h to compile:
    uint64_t myvar = UINT64_C(0) - UINT64_C(1);

    // Not recommended.
    // Requires different cases for different operating systems,
    //  because 'PRIu64' macro is unavailable (only available 
    //  if inttypes.h is #include:d).
    #ifdef __linux__
        printf("myvar=%lu
", myvar);
    #elif _WIN32
        printf("myvar=%llu
", myvar);
    #endif
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...