yogeshwar_misal
yogeshwar_misal

Reputation: 83

What difference does it make when I include <limits> or <limits.h> in my c++ code

Can somebody please explain this?

    #include <iostream>
    #include <limits.h>

or

    #include <iostream>
    #include <limits>

Upvotes: 3

Views: 6385

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106196

<limits> is a C++ Standard Library header providing similar insights to the C header <limits.h> (which is also available in C++ as <climits>), but it is written in a way that's more useful and safe in C++ programs:

  • say you have a template <typename Numeric> ..., and the code inside wants to know the minimum and maximum value of the Numeric type parameter that the user instantiated your template with: you can use std::numeric_limits<Numeric>::min() and ...::max(); if you wanted to access the same values from <climits>, it'd be hard to know which of SCHAR_MIN, SHRT_MIN, INT_MIN, LONG_MIN etc. to use and you'd have to switch between them all yourself - lots of extra code for something so trivial

  • <climits> has lots of macros, and macros don't respect namespaces or scopes the way "normal" C++ identifiers do - their substitutions are made pretty indiscriminately - so they make your program more error prone

  • <limits> gives much more insight about numeric types, such as whether they're signed, the number of base-10 digits they can handle, whether they can represent infinity or not-a-number sentinel values etc. (see the header docs for a fuller list and information)

Upvotes: 11

Nicol Bolas
Nicol Bolas

Reputation: 473926

limits.h is a C standard library header. limits is a C++ standard library header. They contain different things.

There is climits in C++, which offers more or less what limits.h did.

Upvotes: 2

Related Questions