Home > Net >  Parentheses around a constant or around a cast expression involving a constant
Parentheses around a constant or around a cast expression involving a constant

Time:04-27

From time to time I see this code:

#define X1   (13)
#define X2   ((size_t)13)

As I understand, the (outer) () are redundant here. Is that correct?


UPD: Some software development guidelines may require it.

For example: MISRA C:2004, Rule 19.4 (required):

C macros shall only expand to a braced initialiser, a constant, a parenthesised expression, a type qualifier, a storage class specifier, or a do-while-zero construct.

However, MISRA C:2012 has:

#define MY_NULL_2 ( void * ) 0
#define sqrt( x ) ( _BUILTIN_sqrt ( x ) )

CodePudding user response:

I don't believe the first example needs parentheses, but always parenthesizing macro bodies is a reasonable habit.

The second one will produce unexpected grouping if you remove the outer parentheses from the definition and then invoke it in the context X2[a].

CodePudding user response:

As I understand, the (outer) () are redundant here. Is that correct?

In the first case, (13) can cause a problem. See below.
In the the 2nd case ((size_t)13) tends to prevent problems as it insures the cast (which does not have top order of precedence) is applied to only 13 and not some following code.


The () in #define X1 (13) have a disadvantage. Consider stringification.

As (80), the incorrect format string is formed.

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define BUFFER_LEN_WITH (80)
#define BUFFER_LEN_WITHOUT 80

// Could have used either BUFFER_LEN_WITH, BUFFER_LEN_WITHOUT here.
#define BUFFER_SIZE (BUFFER_LEN_WITHOUT   1) 

int main(void) {
  char buffer[BUFFER_SIZE];
  printf("Format: <%s>\n", "%" TOSTRING( BUFFER_LEN_WITH) "s");
  printf("Format: <%s>\n", "%" TOSTRING( BUFFER_LEN_WITHOUT) "s");
  int count = scanf("%" TOSTRING( BUFFER_LEN_WITHOUT) "s", buffer);
  if (count == 1) {
    printf("<%s>\n", buffer);
  }
}

Output

Format: <%(80)s>  <-- Wrong format
Format: <           
  • Related