”;
The C library header <inttypes.h> provides various macros for formatting and working with numeric data type(int). These macros are useful when we are using printf() and scanf() function.
Library Macros
Here, we are going to explore some important key macros of inttypes.h −
Macros of output format specifier − printf() function
- PRIxMAX: This is printf specifier for intmax_t which is equivalent to %x(hexadecimal).
- PRIiMAX: This is printf specifier for intmax_t which is equivalent to %i(integer).
- PRIuLEAST32: This is printf specifier for uint_least32_t which is equivalent to %u(unsigned).
Macros of input format specifier − scanf() function
Similar to printf() function, here are some macros which is used for reading input−
- SCNxMAX: This is scanf specifier for intmax_t which is equivalent to %x(hexadecimal).
- SCNiMAX: This is scanf specifier for intmax_t which is equivalent to %i(integer).
- SCNuLEAST32: This is scanf specifier for uint_least32_t which is equivalent to %u(unsigned).
String function Macros
Below are list of some macros which supports string function −
- strtoimax(str, endptr, base): It is equivalent to strtol() for intmax_t.
- strtoumax(str, endptr, base): It is equivalent to strtoul() for uintmax_t.
- wcstoimax(wcs, endptr, base): It is equivalent to wcstol() for intmax_t.
- wcstoumax(wcs, endptr, base): It is equivalent to wcstoul() for uintmax_t.
Example 1
Following is C library header <inttypes.h> which provide the program for printing integer value with a fixed width.
#include <stdio.h> #include <inttypes.h> int main() { int32_t num1 = 67543; int64_t num2 = 894432590; printf("Formatted output using inttypes.h:n"); printf("num1: %" PRId32 "n", num1); printf("num2: %" PRId64 "n", num2); return 0; }
Output
On execution of above code, we get the following result −
Formatted output using inttypes.h: num1: 67543 num2: 894432590
Example 2
Below the program calculate the factorial of a number using unintmax_t under the header inttypes.h.
#include <stdio.h> #include <inttypes.h> uintmax_t factorial(uintmax_t n) { if (n == 0) return 1; else return n * factorial(n - 1); } int main() { uintmax_t num = 5; printf("Factorial of %" PRIuMAX " = %" PRIuMAX "n", num, factorial(num)); return 0; }
Output
After executing the code, we get the following result −
Factorial of 5 = 120
Example 3
Below the program reads a 64-bit unsigned integer from the user using SCNu64. It then prints the entered value using PRIu64.
#include <stdio.h> #include <inttypes.h> int main() { uint64_t large_number = 9876543210; printf("The entered number: %" PRIu64 "n", large_number); return 0; }
Output
The above code produces the following result −
The entered number: 9876543210
”;