POV-Ray : Newsgroups : povray.off-topic : C/C++ Data Type Ambiguity Backwards : C/C++ Data Type Ambiguity Backwards Server Time
5 Jul 2024 08:57:41 EDT (-0400)
  C/C++ Data Type Ambiguity Backwards  
From: clipka
Date: 21 Aug 2015 08:12:50
Message: <55d715c2$1@news.povray.org>
Okay, I guess everyone who has ever touched C or C++ has at least heard
rumors of this: The standard data types, such as "int", "short int" or
"long int", are anything but. For instance, a "long int" will typically
be 32 bits wide on a 32 bit machine, but 64 bits on a 64 bit machine -
unless you're running Windows, in which case it's still 32 bit. And
"int" will typically be 32 bits wide - unless you're running on a 64 bit
Cray machine, in which case it will be a whopping 64 bit as well. Or on
an embedded computer, in which case it may be as small as 16 bits. Hell,
there are even systems out there where the most fundamental data type,
"char", is not 8 but 16 bits wide!

I've learned this lesson about a decade ago (well, the thing about the
"char" data type, anyway; I might have heard about the other type woes
long before), and also that fortunately the header file <limits.h> (C)
or <climits> (C++) provides some relief: It provides a set of macros
that at least tell you what the minimum and maximum values of those
types are. For instance, "UINT_MAX" will tell you the highest number
that fits in /your/ particular "unsigned int", "SHRT_MAX" will tell you
the same for (signed) "short", and so forth.

Now the data type ambiguity has struck back with a vengeance, right
before my eyes, in the POV-Ray code:

Imagine you need to read a 32 bit integer from a file, and convert it to
a floating point value in the range from 0.0 (correspondng to integer
value 0) to 1.0 (corresponding to integer value 2^32-1). How do you do that?

Well, after reading 4 bytes from the file into a variable that is
supposedly large enough to hold those 4 bytes (we're using an unsigned
int there... whoops), you convert the value straight to floating point
format (giving you a value from 0.0 to 2.0^32-1.0), and then of course
divide by UINT_MAX...

... wait, *WHAT?*

Okay, I can understand how someone might be oblivious enough of the type
issues to shove a 32 bit value into an unsigned int without thinking
twice. But that /constant/ is there exactly because unsigned int is
/not/ guaranteed to be 32 bits wide - and we're seriously using that
very same constant with the /adamant/ presumption that it /is/?

*NOM!*
There. Another bite mark in my desk.

Needless to say, Imma throw this outta the window. (The code, not the
desk. That would bee a tad too heavy.)


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.