4.5. sizeof

The sizeof function tells you the size of an array:

Example 4-9. Using sizeof() on an array


  string *colors;
  int colors_sz;

  colors = ({ "red", "blue", "green", "yellow" });
  colors_sz = sizeof(colors);

colors_sz will equal 4. Indexes for colors_sz go from 0 through 3:


               -------     --------     ---------     ----------
  colors ---> | "red" | , | "blue" | , | "green" | , | "yellow" |
               -------     --------     ---------     ----------

              colors[0]   colors[1]    colors[2]     colors[3]

Note: when you do sizeof on an array that isn't initialized, the result is undefined:


  string *names;
  int x = sizeof(names);

  if (x == 0) {
    write("x == 0");
  }
  if (undefinep(x)) {
    write("undefined");
  }

The code above will write both "x == 0" and also "undefined". While "undefined" is equal to 0, the two values are very different and it's not clear whether these two values will be equivalent in future drivers.

Contrast that with this code:


  string *names = ({ });
  int x = sizeof(names);

  if (x == 0) {
    debugflake("x == 0");
  }
  if (undefinedp(x)) {
    debugflake("undefined");
  }

This will print "x == 0".