How to Save Time with C Programming’s Math Assignment Operators

By Dan Gookin

If you’re a fan of the ++ and – operators in C programming, you’ll enjoy the operators listed below. They’re the math assignment operators, and like the increment and decrement operators, not only do they do something useful, but they also look really cool and confusing in your code.

Operator Function Shortcut for Example
+= Addition x=x+n x+=n
-= Subtraction x=x-n x-=n
*= Multiplication x=x*n x*=n
/= Division x=x/n x/=n
%= Modulo x=x%n x%=n

Math assignment operators do nothing new, but they work in a special way. Quite often in C, you need to modify a variable’s value. For example:

alpha=alpha+10;

This statement increases the value of variable alpha by 10. In C, you can write the same statement by using an assignment operator as follows:

alpha+=10;

Both versions of this statement accomplish the same thing, but the second example is more punchy and cryptic, which seems to delight most C programmers.

ASSIGNMENT OPERATOR HEAVEN

#include <stdio.h>
int main()
{
 float alpha;
 alpha=501;
 printf("alpha = %.1fn",alpha);
 alpha=alpha+99;
 printf("alpha = %.1fn",alpha);
 alpha=alpha-250;
 printf("alpha = %.1fn",alpha);
 alpha=alpha/82;
 printf("alpha = %.1fn",alpha);
 alpha=alpha*4.3;
 printf("alpha = %.1fn",alpha);
 return(0);
}

Exercise 1: Type the source code from Assignment Operator Heaven into your text editor. Change Lines 9, 11, 13, and 15 so that assignment operators are used. Build and run.

When you use the assignment operator, keep in mind that the = character comes last. You can easily remember this tip by swapping the operators; for example:

alpha=-10;

This statement assigns the value -10 to the variable alpha. But the statement

alpha-=10;

decreases the value of alpha by 10.

Exercise 2: Write a program that outputs the numbers from 5 through 100 in increments of 5.