开发者

Should I use the C or C++ implementation for returning a maximum size of a variable type?

From a standards standpoint, should I use the following from the C++ <limits> header?

UCHAR_MAX which is the c implementation or std::numeric_limits<unsigned char>::max() which is the C++ implementation.

The result is equivalent between the two vers开发者_如何学编程ions but should I choose an implementation based on some standard or on readability and portability in this case. Note this implementation must be cross-platform compatible. I am writing C++ code.


If you want the code to be able to compile as C, then you pretty much need to use <limits.h>. If you're writing C++, it's probably better to use the C++ <limits> header instead. The latter lets you write code that will work in templates that can't really be duplicated with the C header:

template <class T>
class mytemplate { 
    T x;
    void somefunc() { x = std::numeric_limits<T>::max(); } // or whatever...
};


Know what language you're writing in, and write in that language. If you're writing C++, use the standard C++ ways of doing things.

Standard C++ is normally cross-platform compatible (there are exceptions, like export, but export is being removed from the C++ Standard anyway). It's usually more readable to stick with C++ constructs than to switch between C and C++ constructs.


You should use <limits> to stay consistant.

On the windows platform, if you include <windows.h>, you might also want to

#define NOMINMAX

to avoid a name conflict with min and max.


When you are using C, std::numeric_limits obviously isn't available.

In C++ it depends on what you want to do - std::numeric_limits<T>::max() is not a constant expression with the current C++ standard.
In these cases an alternative to the C-ish macros would be to use something like Boost.Integers integer traits const_min/const_max which also works in templated contexts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜