문제

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 the wikipedia article for inttypes.h.

Use stdint.h for a minimal set of definitions; use inttypes.h if you also need portable support for these in printf, scanf, et al.

다른 팁

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 "\n", myvar);  
}

One reason you would want to use printf with inttypes.h is because, for example, uint64_t is long unsigned in Linux while uint64_t is long long unsigned in Windows. So, if you were to write the above code and keep it cross-compatible between Linux and Windows, you would do the following:

#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);

    // Requires different cases for different operating systems
    #ifdef __linux__
        printf("myvar=%lu\n", myvar);
    #elif _WIN32
        printf("myvar=%llu\n", myvar);
    #endif
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top