example2_portability_issues_with_unsigned_int.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
#include <limits>

int main() {
    std::vector<int> large_vector;
    large_vector.reserve(1000000);  // Reserve a large, but reasonable amount of memory

    // Simulate a very large size that exceeds unsigned int max value
    size_t actual_size = static_cast<size_t>(std::numeric_limits<unsigned int>::max()) + 1;

    // This assignment might lead to data loss on some systems
    unsigned int size = actual_size;

    std::cout << "Actual size (size_t): " << actual_size << std::endl;
    std::cout << "Stored size (unsigned int): " << size << std::endl;

    if (size == actual_size) {
        std::cout << "Size matches\n";
    } else {
        std::cout << "Size mismatch!\n";
    }

    return 0;
}
Back to size_t