James E. Prater - 1 year ago 104
C++ Question

Optimizing repeating assignment of variable values

In an effort to learn compound assignment in C++, I created the following code to demonstrate what they do:

``````int b05;
int b06 = 13;

b05 = 49;
b05 += b06; // b05 = b05 + b06
cout << "(+=) compound assignment: " << b05 << endl;

b05 = 49;
b05 -= b06; // b05 = b05 - b06
cout << "(-=) compound assignment: " << b05 << endl;

b05 = 49;
b05 *= b06; // b05 = b05 * b06
cout << "(*=) compound assignment: " << b05 << endl;

b05 = 49;
b05 /= b06; // b05 = b05 / b06
cout << "(/=) compound assignment: " << b05 << endl;

b05 = 49;
b05 %= b06; // b05 = b05 % b06
cout << "(%=) compound assignment: " << b05 << endl;

b05 = 49;
b05 >>= b06; // b05 = b05 >> b06
cout << "(>>=) compound assignment: " << b05 << endl;

b05 = 49;
b05 <<= b06; // b05 = b05 << b06
cout << "(<<=) compound assignment: " << b05 << endl;

b05 = 49;
b05 &= b06; // b05 = b05 & b06
cout << "(&=) compound assignment: " << b05 << endl;

b05 = 49;
b05 ^= b06; // b05 = b05 ^ b06
cout << "(^=) compound assignment: " << b05 << endl;

b05 = 49;
b05 |= b06; // b05 = b05 | b06
cout << "(|=) compound assignment: " << b05 << endl;
``````

As you can see, I have to reassign the value of 49 to
`b05`
because the previous operation modifies the values.

Is there a way to go around doing this? Or is there a more efficient method to achieve the same output? (I'd appreciate a code example)

You could do something like this with a macro:

``````#define compound(op) \
b05 = 49; \
b05 op b06; \
std::cout << "(op) compound assignment: " << b05 << std::endl;
``````

Then you call it like this:

``````int b05, b06 = 13;

compound(+=)
compound(/=)
// etc...
``````

What this does, effectively, is text replacement at compile time. In every place you have a `compound(...)`, it will be replaced with the text of the compound macro, with `op` being replaced by whatever you provided in the brackets (in this case, an operator of some sort).

To see this in action, do `g++ -E <codefile>` and you'll see the macro (and any includes) having been expanded out.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download