C Programming/Operators

From Wikiversity
(Redirected from C/Operators)
Jump to navigation Jump to search

Objective[edit | edit source]

  • Learn about the range of operators that C provides:
    • Unary Operators
    • Binary Operators
    • Mathematical Operaters
    • Logical Operators

Lesson[edit | edit source]

Operator syntax[edit | edit source]

The first point to note in C is the order of operations. C has a number of operations, each with a certain priority. Higher levels of priority have all the operators on that level evaluated first - though a couple of levels, instead of having left-to-right priority within that level, have right-to-left priority. To change the order of operations, brackets override any other ordering, like they would inside a maths equation. C uses infix notation, which means that any binary (two operand) operator is placed between the two operands. For unary operators (one operand), the operator is placed before. Note that the exact way that binary operators look could be said to defy the above rule for operator[] and operator(), but this is moot at this point. Typically, the binary operators have a space between themselves and each operand, whereas unary operators are placed with no space. You must be careful using the unary operators since the same symbols can both be binary operators - it can be helpful to use brackets to make sure you don't accidentally get an undesirable result.

Unary operators[edit | edit source]

  • ++ – Pre-increment or post-increment operator. Increases a variable's value by 1.
  • -- – Pre-decrement or post-decrement operator. Decreases a variable's value by 1.
  • ! – Negation operator. Arithmetically or logically negates a variable.

Binary operators[edit | edit source]

  • + – Addition operator. Produces the sum of two variables.
  • - – Subtraction operator. Produces the difference of two variables.
  • * – Multiplication operator. Produces the product of two variables.
  • / – Division operator. Produces the quotient of two variables.
  • % – Modulus operator. Produces the remainder of the division of two variables.

Assignments[edit | edit source]