Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine multiline macros in C with comments at the end of a line

I'm having a brain cramp... is there a way in C to combine a multiline macro with a comment at each line?

e.g.

#define MYARRAY { \
  0.001,   //  5 mV \
  0.002,   // 10 mV \
  0.004,   // 20 mV \
  0.007,   // 35 mV \
  0.013    // 65 mV \
}

I need to define a list of commented array values in a header file that gets used elsewhere, and make it very human-readable.

like image 635
Jason S Avatar asked Sep 24 '15 22:09

Jason S


1 Answers

You can use multiline comments as a way to continue macro definitions from one line to another, instead of backslashes. As described in the C standard, §5.1.1.2/1, comments are reduced to a single space during translation phase 3, while preprocessing directives are executed in phase 4. In effect, that means that newline characters inside a multiline comment do not terminate a preprocessing directive, so you could write:

#define MYARRAY { /*
*/   0.001,   /*  5 mV 
*/   0.002,   /* 10 mV
*/   0.004,   /* 20 mV
*/   0.007,   /* 35 mV
*/   0.013    /* 65 mV
*/ }

Note that line continuations (backslash newline) are removed in phase 2, before comments are recognized as such. So the problem with using C++-style // comments is not that the comment includes the backslash; rather it is that the lines are first concatenated and then the comment extends to the end of the concatenated lines.

like image 51
rici Avatar answered Sep 20 '22 23:09

rici