Wesley Bland Wesley Bland - 3 months ago 30
C Question

Assign two C preprocessor variables in the same command

Is it possible to assign the same value to two C preprocessor macros at the same time? It would behave similar to this normal C code:

a = b = 1;

I know you can do this:

#define VAR1 1
#define VAR2 1

But that a bit of a pain just because there's now code replication and more opportunity to mess things up. Is the only solution this?

#define VAR1 1
#define VAR2 VAR1

EDIT: As the various comments have pointed out, the preprocessor has macros, not variables. Sorry about that.

Kaz Kaz

The ISO C standard doesn't describe any preprocessing directive which assigns the same replacement sequence to multiple symbols. I.e. this sort of thing doesn't exist in the standard:

// fantasy syntax:
#definemulti (A B C) replacement token sequence

Since replacement sequences can contain multiple tokens, there would have to either have to be parentheses somewhere, or some other way to tell where the names end and the replacement sequence.

In 28 years of C coding, I haven't seen any fragment of code anywhere which required a compiler with such an extension.Even if you find a compiler which has this as an extension, the nonportability of using it is hardly worth it.

Introducing this into the language would probably face hurdles because it saves only a small amount of typing.

Moreover, we can make a technical argument that this is a misfeature.

Say we have several compile-time parameters—A, B, and C—for adjusting the behavior of the code. They happen to have the same value, so we define them in one line.

If later they no longer have the same value, the program has to be edited to split off the different values into separate #define constructs. For instance from this:

#definemulti (A B C) 1

to this

#definemulti (A C) 1
#define B 2

this leads to a line diff which touches A and C. The entire definemulti line is replaced with a new one because B migrated out of it. Under a GNU-style context diff, the change might resemble the following:

@@ -x, y  +z, w @@
-#define (A B C) 1
+#define (A C) 1
+#define B 2

Whereas if, in the first place, we have:

#define A 1
#define B 1
#define C 1

the diff hunk is nicer, like this:

@@ -x, y  +z, w @@
 #define A 1
-#define B 1
+#define B 2
 #define C 1

At a glance, we see that A and C are unaffected, and that B changed to 2.