Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF comparison test by value failure ( C++ )

Tags:

c++

object

My current project would be too lengthy to post here, however, this is the single line that produces a really strange behavior, at least as I see it . I use the clip object to store relatively short strings ( maximum size in use in 35 ), however the condition fails when dealing with negative values in start .

I tried adding (const int) in front of clip.length(), but the output wouldn't change :

Any ideas what does this mean ? I'm using G++ on Ubuntu 14.04 .

 void Cut ( const int start, const int stop )
 { if (start > clip.length() ) cout << "start: " << start << " > " << clip.length() << endl;

  ...
 }

enter image description here

like image 353
user43389 Avatar asked Dec 05 '22 03:12

user43389


1 Answers

It is likely that length() returns unsigned int, so another argument, signed int, gets converted to unsigned too, and then comparison takes place.

It is a part of so called usual arithmetic conversions. See the standard:

Expressions [expr]

....

Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

like image 68
AlexD Avatar answered Dec 26 '22 19:12

AlexD