V105. N operand of '?:' operation: implicit type conversion to memsize type.


The analyzer found a possible error inside an arithmetic expression related to the implicit type conversion to memsize type. An overflow error may be caused by the changing of the permissible interval of the values of the variables included into the expression. This warning is almost equivalent to warning V104 with the exception that the implicit type conversion occurs due to the use of ?: operation.

Let's give an example of the implicit type conversion while using operation:

int i32;
float f = b != 1 ? sizeof(int) : i32;

In the arithmetic expression the ternary operation ?: is used which has three operands:

  • b != 1 - the first operand;
  • sizeof(int) - the second operand;
  • i32 - the third operand.

The result of the expression b != 1 ? sizeof(int) : i32 is the value of type size_t which is then converted into type float value. Thus, the implicit type conversion realized for the 3rd operand of ?: operation.

Let's examine an example of the incorrect code:

bool useDefaultVolume;
size_t defaultVolume;
unsigned width, height, depth;
...
size_t volume = useDefaultVolume ?
                        defaultVolume :
                        width * height * depth;

Let's suppose, we're developing an application of computational modeling which requires three-dimensional calculation area. The number of calculating elements which are used is determined according to the variable useDefaultSize value and is assigned on default or by multiplication of length, height and depth of the calculating area. On the 32-bit platform the size of memory which was already allocated, cannot excess 2-3 Gb (depending on the kind of OS Windows) and as consequence the result of the expression width * height * depth will be always correct. On the 64-bit platform, using the opportunity to deal with a larger memory size, the number of calculating elements may excess the value UINT_MAX (4 Gb). In this case an overflow will occur while determining the expression width * height * depth because the result of this expression had type unsigned.

Correction of the code may consist in the changing of the type of the variables width, height and depth to memsize type as follows:

...
size_t width, height, depth;
...
size_t volume = useDefaultVolume ?
                        defaultVolume :
                        width * height * depth;

Or in use of the explicit type conversion:

unsigned width, height, depth;
...
size_t volume = useDefaultVolume ?
                        defaultVolume :
             size_t(width) * size_t(height) * size_t(depth);

In addition, we advise to read the description of a similar warning V104, where one can learn about other effects of the implicit type conversion to memsize type.

Additional materials on this topic:


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++ and C#

goto PVS-Studio;