Search code examples
c++header-files

What is the purpose of limits header files in C++


Why we use the header file called limits in c++.

#include<limits>

What are the uses and who we can use these. Actually i have an assignment to explore the purpose of limits header file and also write a sample programme to use this. and i also i'm new to c++ programming language. I have intermediate knowledge about so i'm not new in programming but new in c++. I haven't read/study about loops, classes and functions in c++. I just need to know about limits header file?


Solution

  • Why do we have this header?

    In (most) other languages, the precise details of numeric types are defined by the language. In C++ there are some things left up to the implementation to define. <limits> provides a mechanism to inspect what the implementation has picked.

    For example, the standard only specifies that int be a numeric type able to represent at least the range [-32767, 32767]. My machine has an int that can represent [-2147483647, 2147483648], and there are others that are even wider.

    A programmer may want their code to fail to compile on an implementation with particular choices.

    int some_complex_algebra(int a, int b)
    {
        static_assert(std::numeric_limits<int>::max() >= 2147483648, "This code assumes at least 32bit 2's complement int");
        // ...
    }