C Operators specify what is to be done to objects with specific type. Operators act on expressions to form a new expression.
There are different types of operators in C.
Arithmetic Operatiors
There are two types of arithmetic (or numerical) operators: first one is unary and second is binary.
The binary operators acts on two operands at a time. It includes plus +, minus −, multiply ∗, divide /, and the modulus operator %.
However, the modulus operator is valid only for non-floating-point types (e.g., char, int, etc), and x % y produces the remainder from the division x / y (e.g., 17 % 7 is equal to 3). The rest of four operators can be used on integer or floating-point types.
Note: The integer division truncates any fractional part (e.g., 18/5 is equal to 3).
The unary operators requires one operand. This type of operators include plus +, minus -, increment ++ and decrement –.
Here is example of unary operators.
double x = 3.2; double y = ++x; double z = x++;
The following table lists the all the arithmetic operators.
Table: Arithmetic operators
The Bitwise Operators
The bitwise logical operators are &, |, ^,left shift <<, right shift >>, and ~. These are essential for low-level programming, such as controlling hardware.
The following table shows the outcome of each operation. In the discussion that follows, keep in mind that the bitwise operators are applied to each individual bit within each operand.
Table: Bitwise Operators
Relational Operators
The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering.
Table : Relational Operators
They work the same as the arithmetic operators (e.g., a > b) but return a Boolean value of either true or false, indicating whether the relation tested for holds. For example, if the variables x and y have been set to 8 and 2, respectively, then x > y returns true. Similarly, x < 5 returns false.
Logical Operators
The logical operators are often used to combine relational expressions into more complicated Boolean expressions.
Following table lists the logical operators and their meaning.
Operator | Meaning |
---|---|
&& | and |
|| | or |
! | not |
The operators return true or false, according to the rules of logic:
a | b | a && b |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
a | b | a || b |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
The ! operator is a unary operator, taking only one argument and negating its value:
a | !a |
---|---|
true | false |
false | true |
We'll discuss more about the application of operators in preceding chapters.