5

I'm new to SO and this is my first question, but I've read the rules and I hope that I won't break any of them.

I have recently started learning programming and have chosen C++ as my first language. Today I have reached a point where I need help to make a proper decision. I'm learning from a 6th edition of C++ Primer Plus and so far author have only introduced C macros and haven't said a single word about numeric_limits template ( at least I think it's a template ) about which I have learned from internet thanks to my curiosity.

So, now I'm a bit lost, because if I understood correctly numeric_limits are a modern way for checking the limits of C++ types thanks to its easy expandability. Furthermore AFAIK among the C macros there aren't definitions for C++11 types like char16_t.

While searching only thing I have found is that question, but provided answers as helpful as they are, unfortunately they doesn't answer what is specifically interesting for me. Also they are mostly quite old actually.

Now, the specific question:

Basing on the needs for speed of code execution, safety and usefulness in future ( I don't care that much about simplicity ) is it better idea to use those old C macros or should I stick to numeric_limits considering the aspects I have mentioned?

Please, forgive me any mistakes in my English. It's not my native language.

4

2 回答 2

7

For most code either C's macros or C++'s std::numeric_limits work fine. In C++03 there was an issue that the min() and max() members couldn't yield constant expressions but this problem is solved with C++11's constexpr.

Both approaches are fully type safe and I would be surprised if you could measure a difference between two versions of a program differing only in the way the type properties are obtained. The primary area where macros are not an alternative are templates: you need a fixed names for the templates entities and the macros just don't work like that (they are also expanded at the wrong time during compilation).

Personally, I always use std::numeric_limits<T>, mainly because I can use it in all of my code and I can remember the names better.

于 2013-12-17T17:35:58.047 回答
1

While both DBL_MAX and std::numeric_limits::max() are perfectly fine (besides the latter is annoying long) you might not use the former when you want to change a value representation having a typedef:

struct X {
   typedef double Real; // may become float
};

Also, having templates you have to use std::numeric_limits.

于 2013-12-17T17:30:50.293 回答