Modulus Assignment (%=) Expression

Summary

Assigns the remainder of a division operation to a variable.

Syntax

variable %= expression

Parameters

variable
The variable, property, or array element to be update.
expression
Any legal expression.

Description

For numeric variables, the %= operator computes the value of the expression on the right; divides it from the variable, property, or array element on the left; gets the remainder from the aforementioned division operation; and, finally, assigns the remainder back to the variable, property, or array element on the left. The expression on the right is evaluated prior to assignment:

1
2
int x = 7;
x %= 4; // x is assigned the value 3

The %= operator is equivalent to the % operator with the left-hand side being the variable, property, or array element to modify and the right-hand side being the expression to divide. Therefore, the following expressions are equivalent:

1
2
x %= 5;    // Equivalent to x = x % 5
x = x % 5; // Equivalent to x %= 5

Examples

Basic Usage
1
2
3
4
5
6
import System;
 
int x = 10;
Console.log(x); // 10
x %= 3;
Console.log(x); // 1

See Also

Share

HTML | BBCode | Direct Link