Reputation: 757
I am writing a program in c++, that stores different data in a binary file. I am running into issues because the size of a data type can change from one system to another. I was wondering if floats are always 4 byte on all windows platforms. The only platform i am building this program for is windows.
Upvotes: 2
Views: 2451
Reputation: 6846
Windows does not define the size of float
-- your compiler defines that.
What Windows defines is a type named FLOAT
in windef.h. It's defined as typedef float FLOAT;
. That's the type name the Win32 API uses and the one you should be using if Windows support is important to you. I doubt any Windows compiler will ever change its format for float
types, but Microsoft certainly could change their typedef
for FLOAT
and that would change what it means to support float
on all versions of Windows.
Upvotes: 0
Reputation: 122383
Not guaranteed by the C++ standard, but most machines today follows ISO/IEC/IEEE 60559:2011, or the identical IEEE-754 floating point standard. By this standard, the single precision float
is 4 bytes.
You can check std::numeric_limits< float >::is_iec559
in <limits>
to make sure.
Upvotes: 3
Reputation: 172428
Yes it has 4 bytes only but it is not guaranteed. You may check the IEEE floating point for reference.
You can check by cross platform behavior like this:-
#include <cassert>
int main () {
assert(sizeof(float) == 4);
// If control goes here you can be sure float is 4 bytes.
}
Upvotes: 1
Reputation: 247969
Yes. Of course, it may be wise to throw a static_assert(sizeof(float)==4, "whatever")
in there (or a plain old non-static assert, if the former is not supported by your compiler), just to (a) document your assumption, and (b) notify you if by some cruel twist of fate your platform suddenly does not have 4-byte floats.
Upvotes: 2