Search code examples
c++stringimplicit-conversion

What causes the overflow of the type conversion of cfloat's INT32_MIN to size_t?


Compiling the code, printed below, in Visual Studio 2019 presents the warning: C26450:... Use a wider type to store the operands.

#include <iostream>
#include <string>
#include <cfloat>

int main()
{
    size_t b = 4;
    std::cout << std::boolalpha << (b < INT32_MIN) << std::endl;

    return 0;
}

the code above returns:

true

Substituting b with the literal 4 returns:

false

INT32_MIN is defined in stdint.h as the literal: (-2147483647i32 - 1).

What in the '<' operation occurs for this overflow error? It acts intuitively when b is type cast to int.

Another note, adding the following indicates no overflow error.

    std::cout << sizeof(size_t) << std::endl;
    std::cout << sizeof(int) << std::endl;

Outputs:

4
4

According to https://en.cppreference.com/w/cpp/types/size_t , size_t is unsigned.

According to https://en.cppreference.com/w/cpp/language/operator_comparison , the < operator causes conversion to the invoking type on the left hand side. What occurs in the conversion between this literal (integer type?) and size_t for it to become equal to 2147483648?


Solution

  • size_t is an unsigned format. This is due to how data is represented in memory. You would have the same behaviour whit INT32_MIN is exactly 0b10000000000000000000000000000000 which is exactly 2^31 / 2147483648 (unsigned). if you represent it as a signed 32bit number then it becomes -2^31 you should checkout : https://www.electronics-tutorials.ws/binary/signed-binary-numbers.html#:~:text=We%20have%20seen%20that%20negative,MSB)%20as%20a%20sign%20bit.&text=The%20representation%20of%20a%20signed,then%20the%20number%20is%20negative.