C & C++

C & C++

Made by DeepSource

Use of sizeof with an expression as operand CXX-W1188

Anti-pattern
Minor

The operator sizeof never evaluates the expression provided as an argument unless it's a variable length array. It only determines the type of the operand. (See reference).

When an expression, like a function invocation, is passed as an argument to sizeof, the function is never called. We can say the same about an expression like z = x + y.

Such an expression should be evaluated and stored in a variable before passing its result to sizeof.

Bad practice

#include <stdio.h>

char get_option(void) {
  char option[2];
  printf("Choice: ");

  if (fgets(option, 2, stdin) == NULL)
    return (char)0;

  return option[0];
}

int main() {
  // In the following line the function `get_option` will never be called and
  // operator `sizeof` will only evaluate the type of the expression i.e. type char
  size_t s = sizeof(get_option());
  // Use s and opt as needed
  return 0;

}

Recommended

#include <stdio.h>

char get_option(void) {
  char option[2];
  printf("Choice: ");

  if (fgets(option, 2, stdin) == NULL)
    return (char)0;

  return option[0];
}

int main() {
  // Call the function `get_option` and invoke operator `sizeof` the return
  // value
  char opt = get_option();
  size_t s = sizeof(opt);
  // Use s and opt as needed
  return 0;
}

Reference

6.5.3.4 [The sizeof and _Alignof operators] -- See point 2 under Section 6.5.3.4