C++ expressions with unsigned and signed operands

For historical reasons in C++ still holds the following behavior when signed and unsigned numbers mix up in the same operand.

In a piece of code like the following:

unsigned int u=1;
int i=-1;
if( i < u )
    cout << "i < u" << '\n';
else
    cout << "i >= u" << '\n';

the outcome would be that the “if condition” is false, even if -1 < 1.

The reason is that a C++ rule (legacy of C rules) states that if two opereands are of the same size and one is unsigned and the other is signed, the signed one is preliminarly converted to unsigned before evaluating the operation.

Therefore here -1 (int) is converted to unsigned int and, due to 2-complement encoding, its “unsigned” representation is bigger than 1.

For an in-depth analysis on the consequent issues and possible approaches to deal with unsigned/signed peaceful living in the same expressions, see this great blog post from “It Hare”.


Deprecated: Creation of dynamic property WP_Term::$cat_ID is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 378

Deprecated: Creation of dynamic property WP_Term::$category_count is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 379

Deprecated: Creation of dynamic property WP_Term::$category_description is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 380

Deprecated: Creation of dynamic property WP_Term::$cat_name is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 381

Deprecated: Creation of dynamic property WP_Term::$category_nicename is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 382

Deprecated: Creation of dynamic property WP_Term::$category_parent is deprecated in /var/www/html/sandroHome/wp-includes/category.php on line 383
This entry was posted in C++ by bartolini@dii.unisi.it. Bookmark the permalink.

Deprecated: Creation of dynamic property WP_Query::$comments_by_type is deprecated in /var/www/html/sandroHome/wp-includes/comment-template.php on line 1528

Leave a Reply