Lovely, Weird Assignment Operators

Some programmers find it charming that C can be so frustratingly obscure. In fact, a lot of the language’s perplexing nature is simply a reflection of its efficiency.

As a case in point, occasionally you need to modify the value in a variable. For example, suppose you need to add 4 to the value of variable x.

One way to do that would be to create a helper variable a:

a = x + 4;
x = a;

I’ll confess that I’ve used code like that. For some reason, my brain finds those two statements more acceptable than the straightforward solution, which is:

x = x + 4;

Because C evaluates the right side of the assignment first, the value of variable x is increased by 4, then the result is assigned back into variable x. It works, but it’s still not as efficient — or as cryptic — as it could be.

The C language features shortcuts that let you modify a variable’s value. These are the assignment operators. You have five of them to choose from:

Addition: +=
Subtraction: -=
Multiplication: *=
Division: /=
Modulus: %=

They’re all charmingly obscure, but they’re also popular; you’ll find the same operators in just about every trendy programming language.

These assignment operators exist to modify single variables, adding, subtracting, multiplying, dividing, or modulussing the variable’s existing value.

Yes, modulussing is a word.

The following code demonstrates how you could use the addition assignment operator to display values from 0 through 100 by increments of 4.

#include <stdio.h>

int main()
{
    int x = 0;

    while(x < 100)
    {
        x += 4;
        printf("%2d ",x);
    }
    putchar('\n');

    return(0);
}

This code could be made tighter by combining the equation at Line 9 with the printf() statement, which would also eliminate the need for curly brackets in the while loop. That would make it more mysterious, but less readable.

Here’s sample output:

 4  8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100

By the way, the trick to remember the operators’ order is simply to try them both ways:

x += 4 makes sense for increasing variable x by 4. But:

x =+ 4 assigns positive 4 the variable x.