Defined constants as an argument to the printf format, why is "+ 0" added?

I am reading a book on C programming, “Advanced Unix Programming,” and in the chapter “Standardization and UNIX Implementation” a program is displayed that prints the values ​​for characters in sysconf and pathconf, the code in this program has several lines that look like this :

#ifdef ARG_MAX printf ("ARG_MAX defined to be %ld\n", (long) ARG_MAX + 0); #else printf ("no symbol for ARG_MAX\n"); #endif 

Whenever a certain constant is used as an argument to printf , it always follows + 0 , it seems to do nothing, because I tried to delete it, and nothing happened. What is the point of adding zero?

+7
c
source share
2 answers

The empty #define pointed out by melpomene in comment is the reason that the + 0 trick.

If any title has #define ARG_MAX (without a value) - an incredible but not impossible state of affairs - the code will still compile, although whether the output is useful is a separate discussion. Replacing an empty space for ARG_MAX leaves (long) + 0 , which remains valid. If, as you would expect, a definition is an appropriately protected expression (possibly in parentheses), adding 0 does not change the value.

In the normal course of events, when the preprocessor evaluates the conditional expression, any identifiers remaining after the macro extension are mapped to zero (ISO / IEC 9899: 2011 §6.10.1 Conditional inclusion):

¶4 ... After all replacements, due to the expansion of the macro and defined unary, the operator was executed, all other identifiers (including those lexical identical to keywords) are replaced by pp-number 0, and then each preprocessing of the token is converted to a token ... .

Although this does not immediately refer to this issue, therefore you sometimes see a conditional expression, for example:

 #if ARG_MAX + 0 > 131072 
+9
source share

This is because this code is autogenerated from an awk program.

The awk (1) program, shown in Figure 2.12, creates a C program that prints the meaning of each pathconf and sysconf character.

An important part of the program is this.

 while (getline <"sysconf.sym" > 0) { printf("#ifdef %s\n", $1) printf("\tprintf(\"%s defined to be %%d\\n\", %s+0);\n", $1, $1) printf("#else\n") printf("\tprintf(\"no symbol for %s\\n\");\n", $1) printf("#endif\n") printf("#ifdef %s\n", $2) printf("\tpr_sysconf(\"%s =\", %s);\n", $1, $2) printf("#else\n") printf("\tprintf(\"no symbol for %s\\n\");\n", $2) printf("#endif\n") } 

Since he does not know what a symbol may contain, he probably defends it, although the book does not explain what its protection is.

0
source share

All Articles