-1

today have found that VS2010 do not support round function in C++ projects. Info about that function have found here. Also noticed that there also no trunc function.

So have tried some stuff and noticed some behavior that may help in such situation.


float a = 2.999;
int b = (int)a;   //gives 2

float a = -2.999;
int b = (int)a;   //gives -2

This works as truncation so I could use that, however I don't want to use code which leads to undefined behavior. So would like to ask if this is defined or undefined behavior.

EDIT: I'm not asking about C++11 as I'm using VS2008.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
ST3
  • 8,826
  • 3
  • 68
  • 92
  • 4.9 is *almost* unchanged from C++98 to C++11, it just uses "prvalue" instead of "rvalue" which does not make any difference. My answer applies to C++98 as well as C++11. – Daniel Frey Oct 13 '13 at 14:03

2 Answers2

5

It is clearly defined in

4.9 Floating-integral conversions [conv.fpint]

1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion trun- cates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. — end note ]

Community
  • 1
  • 1
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
2

It's not undefined behavior.

C++11 §4.9 Floating-integral conversions [conv.fpint]

An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294