Operators in C
Arithmetic Operators
- Addition: +
- Subtraction: -
- Multiplication: *
- Division (both integer and real): /
- integer/integer yields an integer (7/4 is 1)
- float/integer yields a float (7.0/4 is 1.75)
- integer/float yields a float
- float/float yields a float
- Modulus (remainder after integer division): %
- integer%integer yields an integer (7%4 is 3)
Assignment Operators
- Simple assignment: =
- Increment by 1: ++ (equivalent to number = number + 1)
- number++ (number is now 28)
- ++number (number is now 29)
- Decrement by 1: -- (equivalent to number = number - 1)
- number-- (number is now 28)
- --number (number is now 27)
- Compound Assignment : operator= (+=, -=, *=, /=, etc.)
- number += 20 (number is now 47) (equivalent to number = number + 20)
Increment operator example
Example Program
Compound Assignment - do's and don't's
Relational Operators
- Less than: <
- Greater than >
- Less than or equal: <=
- Greater than or equal: >=
- Equal: ==
- Not equal: !=
Logical Operators
Do NOT use the bitwise operators as logical operators. They are not
the same things.
- Bitwise and: &
- Bitwise or: |
Note: C and C++ do short circuit evaluation. Evaluation of a compound
relational expression terminates as soon as the truth or falseness of the
entire expression can be determined. For example:
- (a > b) && (c++ < 12)
If a is not greater than b then the second relationship is
not evaluated since both must be true for the whole thing to be true.
- (a > b) || (c++ < 12)
If a is greater than b then the second relationship is not evaluated
since if either of the parts is true, the whole thing is true.
Pointer Operators
- Declaration specifier: *
- Address of: &
- Dereference: *
Example:
int number = 12;
int *ptr_to_int;
ptr_to_int = &number;
printf("\nValue = %d", *ptr_to_int);
Note: The output is Value = 12