Reputation: 2204
Can you count on a semi-modern processor being able to do floating-point calculations with a piece of data the same size as a pointer? Is there a defined type (possibly in a platform-specific header file) for such a type? I'm after the effect of intptr_t but for floats.
Edit:
I'm not referring to C's float
type, but to floating-point numbers in general.
Edit:
Do I need to just have a script run, testing what the sizes of float
, double, and void *
are for the compiler being used, and generate an appropriate header file to typedef
a type that other code uses?
Upvotes: 2
Views: 863
Reputation: 71525
The closest you will get is:
union floatptr_t {
float f;
void *p;
};
On the down side, this is not exactly what you asked for. On the bright side, it is 100% standard...
[edit]
Yes, you could use sizeof
to compare your pointer size to float
, double
, and long double
, and pick one. But as @R. points out, many pointer values will map to NaN
, so you will not be able to do anything with those floating point values other than cast them back to a pointer... And even that is not guaranteed to work (although it probably will in practice).
But if you cannot do anything with the floating point value except cast it back to a pointer, then you are better off using a union, since that will be just as space-efficient and will actually work portably.
Upvotes: 4
Reputation: 279255
It's certainly very common, since "semi-modern" processors pretty much all have CHAR_BIT 8 and object pointer size either 4 or 8, and pretty much all support IEEE float (32 bits = 4 bytes) and double (64 bits = 8 bytes). So there will normally be a type of the same size. No doubt there are some "weird" architectures out there
But as R.. points out in a comment, that doesn't necessarily mean that all the values of the pointer type can be represented by the floating type, because not all bit patterns are valid values (and some of the ones that are valid are NaNs, and IIRC when you assign a NaN the result is certainly a NaN, but isn't certainly the same NaN). So this type does not get the effect of intptr_t
.
Upvotes: 2
Reputation: 5005
A float
(a.k.a. single precision) is 4 bytes so... yes, maybe.
Note that not all 4 byte values are valid floats, some are NaN
, not a number.
The tone of your question makes me think you've heard something about atomic operations on entities the size of the processor bus. If that's true then DON'T do it
, use explicit atomic operations. They make for more readable code and less bugs.
Upvotes: 1