%=

Description

This is a convenient shorthand to calculate the remainder when one integer is divided by another and assign it back to the variable the calculation was done on.

Syntax

x %= divisor; // equivalent to the expression x = x % divisor;

Parameter Values

  • x: variable. Allowed data types: int.
  • divisor: non zero variable or constant. Allowed data types: int.

Example Code

void setup() { Serial.begin(9600); int x = 7; x %= 5; // x now contains 2 Serial.print("x = "); Serial.println(x); } void loop() { }

The result on Serial Monitor:

COM6
Send
x = 2
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ NOTES AND WARNINGS:

  1. The compound remainder operator does not work on floats.
  2. If the first operand is negative, the result is negative (or zero).

Therefore, the result of x %= 10 will not always be between 0 and 9 if x can be negative.

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES