Question

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 versions 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.

Was it helpful?

Solution

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...
};

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top