C++ type conversion precedence in a return -
i have code being changed compile in 64-bit mode being compiled in win32 various reasons. has caused cleanup work address warnings, i'm picking through code , found looks this:
class foo { public: int foo() { return data_.size()-1; } private: std::vector<int> data_; };
the size() method on stl containers returns unsigned values. return value being cast signed integer value there's conversion occur @ point.
i'm not sure precedence here though. value size() returning cast int , have 1 subtracted, result in return value being -1 if size zero? or subtract 1 unsigned int, possibly doing bad things if container empty when gets called?
thanks!
it unsigned = unsigned - 1; return signed(unsigned) unsigned(0) - 1 == unsigned(max)
from 4.7 integral conversions
a prvalue of integer type can converted prvalue of integer type. prvalue of unscoped enumeration type can converted prvalue of integer type. if destination type unsigned, resulting value least unsigned integer congruent source integer (modulo 2n n number of bits used represent unsigned type). [ note: in two’s complement representation, conversion conceptual , there no change in bit pattern (if there no truncation). — end note ] if destination type signed, value unchanged if can represented in destination type (and bit-field width); otherwise, value implementation-defined.
hence unsigned value greater maximum signed value leads implementation defined behavior.
Comments
Post a Comment