unsigned specifier (%u) in C with Examples
Pre-requisite: Format specifiers in C
The format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, %u, etc.
This article focuses on discussing the format specifier %u.
This unsigned Integer format specifier. This is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in memory. An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables.
Below is the C program to implement the format specifier %u:
The positive integer value can be easily printed using “%u” format specifier.
Case 1: Print char value using %u
Below is the C program to demonstrate the concept:
In the above program, variable c is assigned the character ‘a’. In the printf statement when %u is used to print the value of the char c, then the ASCII value of ‘a’ is printed.
Case 2: Print float value using %u
prog.c: In function ‘main’:
prog.c:11:10: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘double’ [-Wformat=]
Case 3: Print negative integer value using %u