llakais
llakais

Reputation: 1637

Can sizeof() be used to define an array length?

I know that in C, arrays are not supposed to be dynamically sized.

With that in mind, would the following code be allowed? (Trying to declare an array of chars the same length as a double.)

char bytes[sizeof(double)];

My guess is that sizeof operates on its argument during program execution and so this wouldn't be allowed, but I'm not sure.

Also, would there be a difference if this were C++ instead of C?

Upvotes: 7

Views: 3055

Answers (4)

pmg
pmg

Reputation: 108968

Provided its operand is not a VLA, you can use sizeof as a real contant.

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

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

  /* make x's 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 code "running" at https://ideone.com/tKg6dV (http://ideone.com/95bwM; thanks Michael Ansolis)

Upvotes: 1

sashang
sashang

Reputation: 12184

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

There's an exception to this rule in C99 where dynamic arrays are allowed. In that case sizeof is, depending on context, evaluated at runtime (http://en.wikipedia.org/wiki/Sizeof). It doesn't change the legality of the expression in the question.

Upvotes: 9

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143051

Yes, it can and it will not even be a dynamically sized, because sizeof(double) is a compile-time constant.

Upvotes: 6

Alexey Frunze
Alexey Frunze

Reputation: 62048

Yes, it's perfectly fine to do that. sizeof()'s value is determined at compile time.

Upvotes: 1

Related Questions