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; } 7 Answers
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.
1In 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.
2It means the remainder of a division. In your case, divide by 2 and the remainder will be either 0 or 1.
2It means modulo. Usually (x % 2) discriminates odd and even numbers.
Thats the modulo. It returns whats left after division:
10/3 will give 3. - 1 is left.
10%3 gives this 1.
Modulo returns the remainder that is left after division. It is helpful when you're tasked with determining even / odd / prime numbers as an example:
Here's an example of using it to find prime numbers:
int main(void) { int isPrime=1; int n;
cout << "Enter n: "; cin >> n; for (int i=1; i<=n; i++) { for (int j=2; j <= sqrt(static_cast<double>(i)); j++) { if(!(i%j)) { isPrime=0; break; } } if (isPrime) cout << i << " is prime" << endl; isPrime=1; } return 0; }
It's the remainder of division. So like how 5 divided by 2 has a remainder of 1 because 2 goes into 5 2 times but that only equals four, and you got that little extra on the end
5 % 2 == 1
Note that division value isn't being calculated anywhere, so if you wanted both the whole total integer value of the division and it's remainder
int answer = 5 / 2; int remainder = 5 % 2; cout << "5 divided by 2 is " << answer << " with remainder " << remainder; "5 divided by 2 is 2 with remainder 1"