unsigned specifier (%u) in C with Examples
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 for unsigned int %u.
The %u is an unsigned integer format specifier. It is used inside the formatted string to specify the unsigned integer types in functions such as printf(), scanf(), etc. An unsigned Integer means the variable can hold only a positive value.
Syntax
printf("%u", variable_name);
OR
printf("%u", value);
Example
Below is the C program to implement the format specifier %u.
C
#include <stdio.h>
int main()
{
printf ( "%u\n" , 20);
return 0;
}
|
Explanation
The positive integer value can be easily printed using “%u” format specifier.
Unexpected Results When Using %u in C
Case 1: Printing Negative Integer Value Using %u
C
#include <stdio.h>
int main()
{
printf ( "%u" , -20);
}
|
Explanation
-20 will be converted to its positive equivalent and printed as 4294967276 (assuming 32-bit unsigned integers).
Case 2: Print char Value Using %u
C
#include <stdio.h>
int main()
{
char c = 'a' ;
printf ( "%u" , c);
return 0;
}
|
Explanation
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 3: Print float Value Using %u
C
#include <stdio.h>
int main()
{
float f = 2.35;
printf ( "%u" , f);
return 0;
}
|
Output
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=]
printf("%u", f);
^
Explanation
In the above program, %u is used to print a float value which is an incorrect format specifier for float data types.
Related Articles
Last Updated :
05 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...