@@ -227,22 +227,76 @@ $(H2 $(LNAME2 preprocessor, Preprocessor))
227
227
$(H3 $(LNAME2 defines, Preprocessor Macros))
228
228
229
229
$(P ImportC collects all the $(TT #define) macros from the preprocessor run when it is run automatically.
230
- The macros that look like manifest constants, such as:)
231
-
232
- $(CCODE
233
- #define COLOR 0x123456
230
+ Some can be made available to D code by interpreting them as declarations.
231
+ The variety of macros that can be interpreted as D declarations may be expanded,
232
+ but will never encompass all the metaprogramming uses of C macros.
234
233
)
235
234
235
+ $(H4 Manifest Constants)
236
+
237
+ $(P Macros that look like manifest constants, such as:)
238
+
239
+ $(CCODE
240
+ #define COLOR 0x123456
241
+ #define HELLO "hello")
242
+
236
243
$(P are interpreted as D manifest constant declarations of the form:)
237
244
238
245
---
239
246
enum COLOR = 0x123456;
247
+ enum HELLO = "hello";
240
248
---
241
249
242
- $(P The variety of macros that can be interpreted as D declarations may be expanded,
243
- but will never encompass all the metaprogramming uses of C macros.
244
- )
250
+ $(H4 Function-Like Macros)
251
+
252
+ $(P Many macros look like functions, and can be treated as template functions:)
253
+
254
+ $(CCODE
255
+ #define ABC a + b
256
+ #define DEF(a) (a + x))
257
+
258
+ ---
259
+ auto ABC() { return a + b; }
260
+ auto DEF(T)(T a) { return a + x; }
261
+ ---
262
+
263
+ $(P Some macro formulations, however, will not produce the same result:)
264
+
265
+ $(CCODE
266
+ #define ADD(a, b) a + b
267
+ int x = ADD(1, 2) * 4; // sets x to 9)
268
+
269
+ ---
270
+ auto ADD(U, V)(U a, V b) { return a + b; }
271
+ int x = ADD(1, 2) * 4; // sets x to 12
272
+ ---
273
+
274
+ $(BEST_PRACTICE Always use parentheses around arguments and entire expressions:)
275
+
276
+ $(CCODE
277
+ #define ADD(a, b) ((a) + (b)))
278
+
279
+ $(P Another area of trouble is side effects in the arguments:)
280
+
281
+ $(CCODE
282
+ #define DOUBLE(x) ((x) + (x)))
283
+
284
+ ---
285
+ int i = 0;
286
+ DOUBLE(i++);
287
+ assert(i == 2); // D result will be 1, C result will be 2
288
+ ---
289
+
290
+ $(P and treating arguments as references:)
291
+
292
+ $(CCODE
293
+ #define INC(x) (++x))
245
294
295
+ ---
296
+ int i = 0;
297
+ INC(i);
298
+ assert(i == 1); // D result will be 0, C result will be 1
299
+ ---
246
300
247
301
$(H2 $(LNAME2 predefined-macros, Predefined Macros))
248
302
0 commit comments