Chaotic integers in C++

30 Jul 2020 - John Z. Li

Integer types in C++ is really problematic. Languages and compilers should be your friends, but they keep make you surprised.

#include <iostream> 
     
int main() 
{ 
    unsigned int ui = 2; 
    int i = -1; 
    if (ui < i) //true 
    	std::cout << "This shouldn't happen, but happens silently." << std::endl; 
    return 0; 
} 

This means, if you have a function which takes an object of container type as parameter, and someone passes in an empty container, funny things would happen:

#include <iostream> 
#include <vector> 
#include <string> 
     
void fun(std::vector<std::string> vs) { 
    for (int i = 0; i <= vs.size() - 1; ++i) { 
    	std::cout << vs[i] << std::endl; 
    } 
} 
int main() 
{ 
    fun(std::vector<std::string>{"first", "second"}); //works 
    fun(std::vector<std::string>{}); //bang, blow up in your face 
    return 0; 
} 
#include <iostream> 
#include <type_traits> 
int main() 
{ 
    unsigned short a = 0; 
    unsigned short b = 0; 
    decltype(a + b) c = 0; 
    std::cout << "The size of a is: " << sizeof(a) << std::endl //2 
    	<< "The size of c is: " << sizeof(c) << std::endl; //4 
    std::cout << "is c unsigned? " << std::boolalpha 
    	<< std::is_unsigned<decltype(c)>::value << std::endl; //false 
    return 0; 
} 
#include <iostream> 
int main() 
{ 
    short us1 = 0; 
    const short us2 = 1; 
	while (us1 + us2 > us1) { 
	us1++; 
    if (us1 + us2 < us1) 
		std::cout << "will program hit here, if yes, how many times? << std::endl; 
    } 
    return 0; 
} 
\[π‘Ž+𝑏:=π‘Ž+𝑏\,\mod{2^𝑝},\quad π‘Žβˆ—π‘:=π‘Žβˆ—π‘\,\mod{2^𝑝},\]

where $:=$ reads β€œdefined as”. On the other hand, signed integer types are supposed to model the set of integer numbers. The fact that they have limited size and range is of technical reasons. That is why signed number overflow is regarded as undefined behavior. Because it is programmers responsibility that he chooses int type of proper size so that all things work in such a way as if they are normal integer numbers. Since unsigned integers and signed integers are actually of different types, implicit conversion between them should not have been allowed.