1. Home
  2. Docs
  3. C Programming Guides
  4. Operators
  5. Arithmetic Operators

Arithmetic Operators

Introduction

The operators +, –, *, and / work as they do in most other computer languages. You can apply them to almost any built-in data type. When you apply / to an integer or character, any remainder will be truncated. For example, 6/4 will equal 1 in integer division. The modulus operator % also works in C as it does in other languages, yielding the remainder of an integer division. However, you cannot use it on floating-point types. The following code fragment illustrates %:

int x, y;
x = 6;
y = 4;
printf("%d ", x/y);  /* will display 1 */
printf(''%d ", x%y);  /* will display 2, the remainder of the integer division */

x = 1;
y = 3;
printf("%d %d", x/y, x%y); /* will display 0 2 */
OperatorAction
Subtraction, also unary minus
+Addition
*Multiplication
/Division
%Modulus
Decrement
++Increment
Arithmetic Operator

The Increment and Decrement Operators

C includes two useful operators that simplify two common operations. These are the increment and decrement operators, ++ and ––. The operator ++ adds 1 to its operand, and ––subtracts 1. In other words:

x=x+1; 
//can be written as  
x++; 
//or 
++x;

There is, however, a difference between the prefix and postfix forms when you use these operators in a larger expression. When an increment or decrement operator precedes its operand, the increment or decrement operation is performed before obtaining the value of the operand for use in the expression. If the operator follows its operand, the value of the operand is obtained before
incrementing or decrementing it.

x=10;
y=++x; //sets y to 11,
//if you write the code as 
y=x++; // sets y to 10 but x is set to 11

Most C compilers produce very fast, efficient object code for increment and decrement operations — code that is better than that generated by using the equivalent assignment statement. For this reason, you should use the increment and decrement operators when you can. Here is the precedence of the arithmetic operators:

Highest => ++–, -(unary minus), * / %

Lowest => + –

Operators on the same level of precedence are evaluated by the compiler from left to right. Of course, you can use parentheses to alter the order of evaluation. C treats parentheses in the same way
as virtually all other computer languages. Parentheses force an operation, or set of operations, to have a higher level of precedence.

Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *