Unsigned error

Fix the unsigned error

This program has an error that leads to it outputting the wrong answer. Find and fix the error. Think about why the error occurs.

#include <iostream>

int main() {
    unsigned int a = 10;
    unsigned int b = 20;

    int difference = a - b;

    std::cout << "The difference between " << a << " and " << b << " is " << difference << std::endl;

    return 0;
}

Hint

An unsigned operation (like subtraction) will return an unsigned value.

Answer

Subtracting b from a results in a negative number, but since a and b are unsigned int, the result is converted to an unsigned integer, leading to unexpected behavior.

Fixed code:

#include <iostream>

int main() {
    unsigned int a = 10;
    unsigned int b = 20;

    // Use int type for the subtraction to handle negative results correctly
    int difference = static_cast<int>(a) - static_cast<int>(b);

    std::cout << "The difference between " << a << " and " << b << " is " << difference << std::endl;

    return 0;
}
Questions