1. Homepage of Dr. Zoltán Porkoláb
2. Teaching
3. Research
4. Affiliations

# The C programming language – Lecture 4.

## Operators, Expressions, Expression evaluation

Expressions are formed from operators and values or variables. The most simple expressions are similar to the mathematical expressions.

``````A + B * C
``````

What is the meaning?

``````A + (B * C)
``````

Because the precedence of multiplication is higher/stronger than the addition.

What happens, when the operators are on the same precedence level?

``````A * B / C * D
``````

In FORTRAN77, it was not defined, what is the meaning of this expression:

``````((A * B) / C) * D
(A * B * D) / C
(A / C) * B * D
``````

…and if A, B, C, D are INTEGERs, the final result could be different.

In modern languages, expressions are defined by precedence and associativity rules.

In some languages, like Java, associativity always left-to-right. In C associativity is defined by precedence rules. In most precedence groups it is left-to-right, but for unary, ternary and assignment operators they are right-to-left.

## Operators in C

Precedence Operator Description Assoc
Postfix ++ postfix increment L->R
– – postfix decrement
() function call
[] array index
. struct/union member access
-> member access via pointer
(type){list} compound literal (C99)
Unary ++ prefix increment R->L
– – prefix decrement
+ unary plus
unary minus
! logical negation
~ binary negation
(type) type conversion
* pointer indirection
sizeof size of type/object
_Alignof alignment requirement (C11)
Multiplicative * / % multiplication, division, remainder L->R
Shift « » bitwise left/right shift L->R
Relational < <= > >= relational operations L->R
Equality == != equal, not equal L->R
Bitwise & bitwise AND L->R
^ bitwise XOR (exclusive OR) L->R
| bitwise OR L->R
Logical && logical AND L->R
|| logical OR L->R
Ternary ? : conditional expression R->L
Assignment = assignment R->L
+= –= compound assignment
*= /= %=
«= »=
&= |= ^=
Comma , sequence operator L->R

## Evaluation of expressions

Although, expressions are defined by precedence and associativity, how the expression is evaluated is implementation defined.

What will print the following program?

The evaluation order is usually not defined for expressions.

Exceptions are those operations which are sequence points

1. shortcut logical operators ( && || )
2. conditional operator ( ? : )
3. comma operator

Also, when a function is called, first the operands are evaluated, (but in undefined order)