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

我的未来我决定 提交于 2019-12-04 21:52:11

<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 indescriminately - 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)

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!