IBM Support

Assigning a negative float value to an unsigned integral type yields an undefined value stored in the type

Troubleshooting


Problem

Attempts to assign a negative float value to an unsigned int or an unsigned short variable and compiled with IBM C/C++ compiler (xlc, xlC or xlc++) on AIX, results an undefined value stored in the unsigned int variable.

Symptom

Example:


========Start of test.cpp=============
#include "stdio.h"
int main()
{
   float i=-1.2;
   unsigned int j=i;
   unsigned short k=i;
   printf("i is %f, j is %d, k is %d n", i, j, k);
   return 0;
}
========End of test.cpp============

Using XL C/C++ on AIX:


$xlC test.cpp
$./a.out
i is -1.200000, j is 0, k is 0


With the test case above, the value stored in the unsigned int happens to be zero. In test.cpp, negative float values can not be represented in an unsigned integer or unsigned short format.

Cause

Casting a negative float value to an unsigned integral type is not a defined behavior. In such cases, the C++ Standard mentions that the conversion truncates and the behavior is undefined if the truncated value cannot be represented in the destination type.

In the above test case, the truncated value of -1.2 is -1 which cannot be represented in an unsigned int. As a result, the behavior is undefined.

For the same reason casting a negative float to an unsigned short or char is undefined.

Resolving The Problem

Either one of the following changes can be made to test.cpp:

  • Assign the float value to a signed int instead of an unsigned int

    or

  • Take the float absolute value before assigning it to an unsigned int

[{"Product":{"code":"SSJT9L","label":"XL C\/C++"},"Business Unit":{"code":"BU054","label":"Systems w\/TPS"},"Component":"Compiler","Platform":[{"code":"PF002","label":"AIX"}],"Version":"10.1;11.1;12.1","Edition":"","Line of Business":{"code":"LOB08","label":"Cognitive Systems"}}]

Document Information

Modified date:
08 August 2018

UID

swg21264561