mohsen_og
mohsen_og

Reputation: 783

C++ double pointer array to float conversion

What is a correct way to convert double to float in c++. Is the conversion implicit?

Question 1: Consider double d = 5.0; and float f;

Which one is correct?

Question 2: Now consider we have

char *buffer = readAllBuffer(); 
double *d = (double*)(buffer + offset);
float f;

Which one is now correct?

Thanks in advance!

Upvotes: 1

Views: 1302

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283951

You do have one major issue. This is not allowed:

double *d = (double*)(buffer + offset);

It violates strict aliasing and quite possibly alignment requirements. Instead you need to use memcpy:

double d;
memcpy(&d, buffer + offset, sizeof d);
float f = d;

Either of the cast alternative can be substituted for the last line, the important change is from dereferencing an pointer with incorrect type and alignment to making a bytewise copy.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234885

They all boil down to the same thing, and the use of arrays is a red herring. You can indeed write

float f = d;

Some folk argue that a static_cast makes code more readable as it sticks out so clearly. It can also defeat warnings that some compilers might issue if a less long-winded form is used.

Naturally of course since a double is a superset of float, you might lose precision. Finally, note that for

float f1 = whatever;
double d1 = f1;
float f2 = d1;

, the C++ standard insists that f1 and f2 must be the same value.

Upvotes: 6

Related Questions