# C++ What does the percentage sign mean?

### Question

I got this c++ macro and wonder what they mean by code%2 (the percentage sign) ?

``````#define SHUFFLE_STATEMENT_2(code, A, B)
switch (code%2)
{
case 0 : A; B; break;
case 1 : B; A; break;
}
``````
1
11
1/3/2015 10:19:05 PM

It is for taking a modulus.

Basically, it is an integer representation of the remainder.

So, if you divide by 2 you will have either 0 or 1 as a remainder.

This is a nice way to loop through numbers and if you want the even rows to be one color and the odd rows to be another, modulus 2 works well for an arbitrary number of rows.

25
10/1/2009 2:53:21 PM

In case somebody happens to care: % really returns the remainder, not the modulus. As long as the numbers are positive, there's no difference.

For negative numbers there can be a difference though. For example, -3/2 can give two possible answers: -1 with a remainder of -1, or -2 with a remainder of 1. At least as it's normally used in modular arithmetic, the modulus is always positive, so the first result does not correspond to a modulus.

C89/90 and C++98/03 allow either answer though, as long as / and % produce answers that work together so you can reproduce the input (i.e. -1x2+-1->-3, -2x2+1=-3).

For newer versions of the standards (C99, C11 and C++11) there's no longer any choice: integer division must round toward 0. For example -3/2 must give -1 with a remainder of -1. -3/2 giving -2 with a remainder of 1 is no longer allowed.