liveBook · Manning

Sizeof operator

As explained in Modern C, Third Edition

The sizeof operator is a C unary operator that yields the size in bytes of a type or object representation.

The C sizeof operator yields an object or object type's size in bytes. For an array A, sizeof A divided by sizeof A[0] gives its element count. section 6.1.3 section 12.1

Computing an array length

double values[] = { 1.0, 2.0, 3.0, 4.0 }; size_t count = sizeof values / sizeof values[0]; Here, sizeof values measures the entire array and sizeof values[0] measures one element, so count is 4. section 6.1.3

Key rules:

  • Use sizeof(char), which is 1 by definition; objects can be viewed as arrays of unsigned char[sizeof object]. section 12.1
  • Write sizeof object with or without parentheses; write sizeof(type) with parentheses. section 12.1
  • Do not use sizeof on an array parameter: its innermost dimension is lost when passed to a function. section 6.1.4
Listing 6.1 A function with an array parameter
#include <stdio.h>

void swap_double(double a[static 2]) {
  auto tmp = a[0];
  a[0] = a[1];
  a[1] = tmp;
}
int main(void) {
  double A[2] = { 1.0, 2.0, };
  swap_double(A);
  printf("A[0] = %g, A[1] = %g\n", A[0], A[1]);
}

A small function demonstrates that an array parameter operates directly on the caller's array rather than preserving a complete array object. section 6.1.4

How Modern C, Third Edition covers it

How deep it goes
Defines object and type forms and the byte model, but defers the pointer mechanism behind array parameters.
Examples
Uses array-length division and a swapping function with an array parameter.
What it assumes
Assumes arrays and function parameters, while defining bytes, object sizes, and sizeof syntax explicitly.
What you can do after
Apply it to calculate array lengths and reason about object representations, while avoiding it on array parameters.
How it connects
Connects sizeof to arrays, variable-length arrays, array parameters, object types, and character types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.