Is there any difference between this two macros?

the*_*ver 3 c c-preprocessor

I find no difference between these two macros except the parentheses surrounding the macro in the first one.

Is it a matter of readability or is it a way to deal with the priority of operators?

#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)
Run Code Online (Sandbox Code Playgroud)

Eri*_*hil 7

Yes, there is a difference. The parentheses are needed so that the result of the macro is evaluated as a single expression, rather than being mixed with the surrounding context where the macro is used.

The output of this program:

#include <stdio.h>

#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)

int main(void)
{
    int x[4];
    printf("%zu\n", 13 % TAM_ARRAY (x));
    printf("%zu\n", 13 % TAM_ARRAY2(x));
}
Run Code Online (Sandbox Code Playgroud)

is, in a C implementation where int is four bytes:

1
3

because:

  • 13 % TAM_ARRAY (x) is replaced by 13 % (sizeof(x)/sizeof(*x)), which groups to 13 % (sizeof(x) / sizeof(*x)), which evaluates to 13 % (16 / 4), then 13 % 4, then 1.
  • 13 % TAM_ARRAY2(x) is replaced by 13 % sizeof(x)/sizeof(*x), which groups to (13 % sizeof(x)) / sizeof(*x), which evaluates to (13 % 16) / 4, then 13 / 4, then 3.

Along these lines, TAM_ARRAY would be better to include parentheses around the second instance of a as well:

#define TAM_ARRAY(a) (sizeof(a)/sizeof(*(a)))
Run Code Online (Sandbox Code Playgroud)

  • @chqrlie:谢谢。实际上,它实际上可能会出现,因为有时会使用键将键以包装方式插入到数组中,因此将索引计算为键模数组大小的其余部分。我只是去了C标准,并寻找了一些会表现出问题的运算符。 (2认同)