Course contentsShow
← C
Lesson 90 of 1,2192. Variables and TypesFree lesson

The `unsigned` keyword

The unsigned keyword

What you'll learn: You’ll learn how to double the positive range of an integer variable by telling the computer to ignore negative numbers.

The sign of the number

By default, most integer types in C are "signed." This means they use one tiny piece of their memory—a single bit—to act like a plus or minus sign. Because that bit is busy acting as a signpost, it can’t be used to represent the size of the number itself.

Think of a small ruler that is 10 centimeters long. If you place "zero" in the middle, you can measure 5cm to the right (positive) and 5cm to the left (negative). The ruler covers a total span of 10, but the highest number you can reach is only 5.

Using unsigned

When you add the unsigned keyword before a variable type, you are telling C: "I promise this number will never be negative."

Going back to our ruler analogy, using unsigned is like moving the "zero" to the very far left edge. Now, instead of measuring from -5 to +5, you can measure from 0 all the way to 10. You haven't changed the size of the ruler, but you have doubled your capacity for positive numbers.

Why use it?

You use unsigned when negative values make no logical sense. For example, a person’s age, the number of pixels on a screen, or the amount of memory in a computer cannot be negative. By using unsigned, you gain extra "headroom" for large positive values.

#include <stdio.h>

int main() {
    // A standard signed integer (can be positive or negative)
    int temperature = -10;

    // An unsigned integer (can only be 0 or positive)
    // This allows for much larger positive values
    unsigned int distanceInMeters = 50000;

    printf("Distance: %u", distanceInMeters);
    
    return 0;
}

In the code above, we use %u instead of %d to print the unsigned value. If you accidentally try to store a negative number in an unsigned variable, C won't stop you, but the result will "wrap around" to a massive, unexpected positive number. Always ensure your data fits the type!

Key takeaway

The unsigned keyword removes the ability to store negative numbers, effectively doubling the maximum positive value a variable can hold.