views:

159

answers:

4

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.

+9  A: 

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...
};
Jerry Coffin
Did you mean `static T`? This won't work pre-C++0x due to function calls not being allowed in constant expressions.
Georg Fritzsche
@Georg:Not really -- I just didn't bother to put the code into a function where it really belongs.
Jerry Coffin
A: 

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.

Georg Fritzsche
According to Boost.integers const_max is equivalent to std::numeric_limits<T>::max().
Elpezmuerto
@Elpez: Equivalent regarding their value, yes. But they are not functions, they are `static const` integrals, which means they can be used with e.g. `case` or to initialize `static const` integral members.
Georg Fritzsche
A: 

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.

David Thornley
A: 

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.

5ound
I like to avoid `<windows.h>` due to cross-compatibility issues
Elpezmuerto