MESSAGE
DATE | 2010-02-02 |
FROM | Ruben Safir
|
SUBJECT | Subject: [NYLXS - HANGOUT] C++ Workshop I datatypes cont..
|
On Tuesday 02 February 2010 09:33:42 Henning Follmann wrote: ... > When talking about data types I think it is important for the sake of > better coding to use C++ constructs rather than pulling these old c > limits.h. > > C++ data types, unlike java, are implementation dependent. To deal with > this the C++ standard provides for the basic data type (short, int, float, > double, char, unsigned, long) a standardized interface. > > numeric_limits is the C++ way to deal with the implementation details > of basic types.
That is interesting, as it means you can find out at run-time what the underlying size and maximum numbers a variable type can contain, however I can't see using this in order to /choose/ a variable type at runtime.
I tried doing it anyway as an exercise to see what that would look like. So, say I wanted an unsigned variable with exactly 16 bits. Here are two implementations.
First what I would normally want to do:
#include #include
using namespace std;
int main(void) { uint16_t port_number;
cout << "Sizeof port_number (bytes): " << sizeof(port_number) << endl; return 0; }
The second uses dynamic type assignment using a run-time test:
#include #include
using namespace std;
int main(void) { if (numeric_limits::max() > 65535) { cout << "uint too big, using ushort" << endl; unsigned short *p = new unsigned short; cout << "Size of p is (bytes): " << sizeof(*p) << endl; } else { unsigned int *p = new unsigned int; cout << "Size of p is (bytes): " << sizeof(*p) << endl; }
cout << "Minimum value for ushort: " << numeric_limits::min() < cout << "Maximum value for ushort: " << numeric_limits::max() < cout << "Minimum value for uint: " << numeric_limits::min() < cout << "Maximum value for uint: " << numeric_limits::max() < return 0; }
This gives rise to another more subtle problem with the latter program. One is that I haven't used free(), making the program leak memory, but there's another: the pointer p only exists within the if{} block due to scope limiting in C++. Try to use p outside of the if{} block and you'll get a compiler error.
Too messy. I don't think it was meant to be used this way.
-- Chris
--
Chris Knadle Chris.Knadle-at-coredump.us _____________________________________________________________________________ Hire expert Linux talent by posting jobs here :: http://jobs.nylug.org The nylug-talk mailing list is at nylug-talk-at-nylug.org The list archive is at http://nylug.org/pipermail/nylug-talk To subscribe or unsubscribe: http://nylug.org/mailman/listinfo/nylug-talk
|
|