Search code examples
c++integerc-standard-library

How do I use UINT64_MAX standard library macro?


While learning C++ I recently came across the usage of macros and learnt that there are many standard macros such as this one (and many others for Integers) :

#include <cstdint>    
UINT64_MAX

(from https://en.cppreference.com/w/cpp/types/integer)

I don't really understand what it is even though the name speaks for itself (i guess?) and how to use it in a code.

EDIT : I know this macro returns the max value that a uint64_t can contain. What I don't know is how and when this should be used. If you could give a written example and a "common" scenario, it would be perfect.


Solution

  • UINT64_MAX is used to return the maximum value a uint64_t can contain. A common scenario would be to cast a double into a uint64_t. We would :

    1. make sure that the uint64_t variable it is casted to is greater than or equal to zero.
    2. it's less than or equal to UINT64_MAX (std::numeric_limits would apparently work too.)

    Here is an example :

    #include <iostream>
    #include <cstdint>
    
    int main() {
        constexpr double a = 6383464.632463948;
    
        if (b >= 0 && b <= UINT64_MAX) {
            uint64_t b = (uint64_t)a; // Cast the double into the uint64_t variable
            std::cout << "Conversion from double to uint64_t is valid" << std::endl;
            std::cout << "b value is " << b << std::endl;
        }
        else {
            std::cout << "Conversion from double to uint64_t is not valid" << 
    std::endl;
        }
    }