Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to guarantee exact size of double in C?

Tags:

c

So, I am aware that types from the stdint.h header provide standardized width integer types, however I am wondering what type or method does one uses to guarantee the size of a double or other floating point type across platforms? Specifically, this would deal with packing data in a void*

#include <stdio.h>
#include <stdlib.h>

void write_double(void* buf, double num)
{
  *(double*)buf = num;
}

double read_double(void* buf)
{
  return *(double*)buf;
}


int main(void) {
  void* buffer = malloc(sizeof(double));
  write_double(buffer, 55);
  printf("The double is %f\n", read_double(buffer));
  return 0;
}

Say like in the above program, if I wrote that void* to a file or if it was used on another system, would there be some standard way to guarantee size of a floating point type or double?

like image 996
Josh Weinstein Avatar asked Jan 03 '23 05:01

Josh Weinstein


1 Answers

How to guarantee exact size of double in C?

Use _Static_assert()

#include <limits.h>

int main(void) {
  _Static_assert(sizeof (double)*CHAR_BIT == 64, "Unexpected double size");
  return 0;
}

_Static_assert available since C11. Otherwise code could use a run-time assert.

#include <assert.h>
#include <limits.h>

int main(void) {
  assert(sizeof (double)*CHAR_BIT == 64);
  return 0;
}

Although this will insure the size of a double is 64, it does not insure IEEE 754 double-precision binary floating-point format adherence.

Code could use __STDC_IEC_559__

An implementation that defines __STDC_IEC_559__ shall conform to the specifications in this annex` C11 Annex F IEC 60559 floating-point arithmetic

Yet that may be too strict. Many implementations adhere to most of that standard, yet still do no set the macro.


would there be some standard way to guarantee size of a floating point type or double?

The best guaranteed is to write the FP value as its hex representation or as an exponential with sufficient decimal digits. See Printf width specifier to maintain precision of floating-point value

like image 151
chux - Reinstate Monica Avatar answered Jan 16 '23 03:01

chux - Reinstate Monica