CSharp/C# Tutorial - C# Arithmetic Operators






The arithmetic operators (+, -, *, /, %) are defined for all numeric types.

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Remainder after division

Increment and Decrement Operators

The increment and decrement operators (++, --) increment and decrement numeric types by 1.

The operator can either follow or precede the variable, depending on whether we want its value before or after the increment/decrement.

For example:


int x = 0, y = 0; 
Console.WriteLine (x++); // Outputs 0; x is now 1 
Console.WriteLine (++y); // Outputs 1; y is now 1 





Integral division

Division operations on integral types always truncate remainders.

Dividing by a variable whose value is zero generates a runtime error.

Dividing by the literal or constant 0 generates a compile-time error.

Integral overflow

At runtime, arithmetic operations on integral types can overflow.

For example, decrementing the minimum possible int value results in the maximum possible int value:


int a = int.MinValue; 
a--; 
Console.WriteLine (a == int.MaxValue); // True 

The checked operator tells the runtime to generate an OverflowException rather than overflowing silently in case of overflow.

The checked operator affects expressions with the ++, --, +, -, *, /, and explicit conversion operators between integral types.

The checked operator has no effect on the double and float types.

The checked operator has no effect on the decimal type which is always checked.

checked can be used around either an expression or a statement block.

For example:


int a = 1000000; 
int b = 1000000; 
//from w  w w  . j  a v  a  2s.  c o  m
int c = checked (a * b); // Checks just the expression. 

// Checks all expressions  in statement block. 
checked{       
    ... 
    c = a * b; 
    ... 
} 

We can check all arithmetic overflow for a program by compiling with the /checked+ command-line switch.

To disable overflow checking for specific expressions or statements, use the unchecked operator.

For example, the following code will not throw exceptions-even if compiled with /checked+:


int x = int.MaxValue; 
int y = unchecked (x + 1); 
unchecked { int z = x + 1; } 

Regardless of the /checked compiler switch, expressions evaluated at compile time are always overflow-checked-unless we apply the unchecked operator:


int x = int.MaxValue + 1;             // Compile-time error 
int y = unchecked (int.MaxValue + 1); // No errors 





Bitwise operators

C# supports the following bitwise operators:

OperatorMeaningSample expressionResult
~Complement~0xfU0xfffffff0U
&And0xf0 & 0x330x30
|Or0xf0 | 0x330xf3
^Exclusive Or0xff00 ^ 0x0ff00xf0f0
<<Shift left0x20 << 20x80
>>Shift right0x20 >> 10x10