Open In App

unsigned specifier (%u) in C with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to implement
// the format specifier
#include <stdio.h>
 
// Driver code
int main()
{
    // Print value 20 using %u
    printf("%u\n", 20);
    return 0;
}


Output

20

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




// C program to demonstrate
// the above concept
#include <stdio.h>
 
// Driver code
int main()
{
    // The -20 value is converted
    // into it's positive equivalent
    // by %u
    printf("%u", -20);
}


Output

4294967276

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




// C program to demonstrate
// the concept
#include <stdio.h>
 
// Driver code
int main()
{
    // ASCII value of a character
    // is = 97
    char c = 'a';
 
    // Printing the variable c value
    printf("%u", c);
    return 0;
}


Output

97

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




// C program to demonstrate
#include <stdio.h>
 
// Driver code
int main()
{
    float f = 2.35;
 
    // Printing the variable f value
    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
Previous
Next
Share your thoughts in the comments
Similar Reads