An amazing trick to print maximum value of an unsigned integer in C

By: IncludeHelp, on 29 JAN 2017

Today, I am here with a trick to print the maximum value of an unsigned integer in c programming language. This trick and example is based on 32 bits compiler where unsigned integer takes 4 bytes in the memory.

Consider the following steps:

Step 1: Declare an unsigned integer variable using unsigned int.

Step 2: Assign -1 to the variable.

unsigned int maxValue=-1;

Step 3: Print the value with %u format specifier.

Now, maximum value of an unsigned integer will print on the screen.


Here is the example:

#include <stdio.h>
int main()
{
	unsigned int maxValue=-1;
	
	printf("Maximum value of unsigned int is: %u\n",maxValue);
	
	return 0;
}

Output

    Maximum value of unsigned int is: 4294967295

Explanation

A signed type variable contains both kind of values –ve to +ve but when any unsigned type variable is assigned with -1, it represents the maximum value of that type and %u is a format specifier which prints the value in unsigned format (without sign).

See the below captured image of calculator with maximum value of 32 bits (4 bytes), here I set all 32 bits.

How to print maximum value of an unsigned int in c language



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.