Can sizeof () be used to determine the length of an array?

I know that in C arrays should not have dynamic size.

With that in mind, is the following code valid? (Trying to declare an array of characters the same length as a double.)

char bytes[sizeof(double)];

I assume that it is sizeofworking on its argument at runtime, so this will not be allowed, but I'm not sure.

Also, will there be a difference if it is C ++ instead of C?

+5
source share
4 answers

The sizeof expression is evaluated at compile time (not by the preprocessor by the compiler), so the expression is legal.

C99, . sizeof, , (http://en.wikipedia.org/wiki/Sizeof). .

+7

, , , sizeof(double) .

+6

Yes, that’s fine. The value of sizeof () is determined at compile time.

+1
source

If its operand is not a VLA, you can use it sizeofas a real constant.

#include <stdio.h>
#include <string.h>

int main(void) {
  double x;
  unsigned char dbl[sizeof x];                             /* real constant */

  /* make x format have a 1 bit on the "correct" place */
  x = 32.000000000000004;
  memcpy(dbl, &x, sizeof x);
  switch (dbl[0]) {
    case sizeof *dbl: puts("1"); break;                    /* real constant */
    case 0: puts("0"); break;
    default: puts("other");
  }
  return 0;
}

See the code "running" at http://ideone.com/95bwM

+1
source

All Articles