Site icon ucdev

C Operators Explained: Types, Precedence and Associativity

vertical shot of woman writing on computer in an office and colour code on a computer screen

Photo by Mizuno K on Pexels.com

Operators are fundamental building blocks of the C programming language. They allow programmers to perform calculations, compare values, manipulate individual bits, access memory, and control program logic.

Although most operators are straightforward when used individually, combining several operators in a single expression can sometimes produce unexpected results.

To understand how expressions work in C, we need to become familiar with three important concepts:

In this article, we will explore these concepts with practical examples, including pointer expressions commonly encountered in embedded C programming.

Types of Operators in C

C operators can be classified in several ways. One common classification is based on the number of operands they require. An operand is a value or expression on which an operator acts.

Based on the number of operands, operators can be divided into three categories: unary, binary, and ternary.

Unary Operators

Unary operators work with a single operand. Some common unary operators in C include:

OperatorDescriptionExample
+Unary plus+a
–Unary minus-a
++Increment++a
—Decrement–a
!Logical NOT!a
~Bitwise NOT~a
*Pointer dereference*ptr
&Address-of&a
sizeofSize of an object or typesizeof(a)

For example:

int a = 5;
int b = -a;  // b = -5

++a;         // a = 6

Some unary operators have different behavior depending on whether they appear before or after an operand. For example, the increment operator ++ can be used in two forms:

int a = 5;
int b = ++a;  // Prefix increment

int c = 5;
int d = c++;  // Postfix increment

For prefix increment, a is incremented first, and the resulting value is used to initialize b. Both variables (a i b) contain 6. With postfix increment the original value of a is used to initialize c, and a is incremented afterward. The resulting values are c and d both equals 5;

This distinction becomes especially important when increment operators are combined with pointers.

Binary Operators

Binary operators work with two operands. For example:

int a = 10;
int b = 5;

int result = a + b;

The addition operator + takes two operands, a and b, and produces their sum. C provides several categories of binary operators.

Arithmetic operators

OperatorDescription
+Addition
–Subtraction
*Multiplication
/Division
%Remainder

Relational and equality operators

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical operators

OperatorDescription
&&Logical AND
| |Logical OR

Bitwise operators

OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise XOR
<<Left shift
>>Right shift

Bitwise operators are particularly important in embedded programming because they allow direct manipulation of individual bits. For example, consider a variable representing an 8-bit hardware register:

#include <stdint.h>

uint8_t reg = 0x00;

reg |= (1U << 3);   // Set bit 3
reg &= ~(1U << 3);  // Clear bit 3
reg ^= (1U << 3);   // Toggle bit 3

These operations are frequently used when configuring peripheral registers, controlling GPIO pins, or processing communication protocol fields.

Assignment operators

C also provides assignment and compound assignment operators:

int a = 10;

a += 5;  // Equivalent to a = a + 5
a -= 2;  // Equivalent to a = a - 2
a *= 3;  // Equivalent to a = a * 3

Other compound assignment operators include /=, %=, &=, |=, ^=, <<=, and >>=.

Ternary Operator

C has one ternary operator, the conditional operator ?:. It works with three operands and provides a compact way to choose between two expressions based on a condition. Its syntax is:

condition ? expression_if_true : expression_if_false;

For example:

int a = 10;
int b = 20;
int max = (a > b) ? a : b;

If a > b is true, the result is a. Otherwise, the result is b.

In this example, max is initialized to 20.

The conditional operator can sometimes replace a simple if-else statement, although complex nested conditional expressions can reduce code readability.

Member Access, Array Subscript, and Pointer Operators

Besides arithmetic and logical operations, C provides operators for accessing structures, arrays, and memory addresses. These operators are especially useful when working with data structures and hardware registers.

Array Subscript Operator []

The array subscript operator accesses an element of an array.

int numbers[3] = {10, 20, 30};
int value = numbers[1]; // value = 20

In C, array indexing is defined in terms of pointer arithmetic. The expression:

numbers[1]

is equivalent to:

*(numbers + 1)

This relationship is one of the fundamental connections between arrays and pointers in C.

Structure Member Access Operator .

The dot operator accesses a member of a structure or union.

struct Sensor {
    int temperature;
    int humidity;
};

struct Sensor sensor = {25, 60};
int temp = sensor.temperature;

Here, the . operator accesses the temperature member of the sensor structure.

Pointer Member Access Operator ->

The arrow operator accesses a structure or union member through a pointer.

struct Sensor *ptr = &sensor;
int temp = ptr->temperature;

The expression:

ptr->temperature

is equivalent to:

(*ptr).temperature

The parentheses are important because the member access operator . has higher precedence than the dereference operator *.

Address-of Operator &

The address-of operator returns the address of an object.

int value = 10;
int *ptr = &value;

Here, ptr stores the address of value.

Dereference Operator *

The dereference operator accesses the object pointed to by a pointer.

int value = 10;
int *ptr = &value;

*ptr = 20;

After this operation, value contains 20.

Notice that the * symbol has different meanings depending on its context.

int *ptr;       // Pointer declaration
int result = a * b; // Multiplication
result = *ptr;  // Dereference

The same symbol can therefore represent different operations.

What Is Operator Precedence in C?

Operator precedence determines how operators are grouped when multiple operators appear in an expression.

Consider the following example:

int result = 2 + 3 * 4;

Multiplication has higher precedence than addition, so the expression is grouped as:

int result = 2 + (3 * 4);

The result is 14, not 20. Parentheses can be used to explicitly control grouping:

int result = (2 + 3) * 4;

Now the result is 20.

Operator Precedence Table

The following table summarizes the main C operator precedence levels, from highest to lowest.

LevelOperatorsAssociativity
1(), [], ., ->, postfix ++, --Left to right
2Prefix ++, --, unary +, -, !, ~, *, &, sizeof, _AlignofRight to left
3*, /, %Left to right
4+, -Left to right
5<<, >>Left to right
6<, <=, >, >=Left to right
7==, !=Left to right
8&Left to right
9^Left to right
10|Left to right
11&&Left to right
12| |Left to right
13?:Right to left
14=, +=, -=, *=, /=, and other compound assignmentsRight to left
15,Left to right

This table uses the traditional precedence presentation. Modern C standards also include additional operators and syntax, such as _Alignof and C23’s alignof.

An important point is that operator precedence determines grouping, not the order in which operands are evaluated. We will return to this distinction later.

4. Understanding Operator Associativity

Operator associativity determines how operators with the same precedence are grouped. For example, subtraction has left-to-right associativity.

int result = 10 - 5 - 2;

The expression is grouped as:

int result = (10 - 5) - 2;

Therefore, the result is 3. Assignment operators, on the other hand, have right-to-left associativity.

int a, b, c;
a = b = c = 10;

This expression is grouped as:

a = (b = (c = 10));

As a result, all three variables receive the value 10. Associativity becomes particularly important when combining operators that have the same precedence.

Operator Precedence with Pointers

Pointer expressions are a common source of confusion in C, particularly when increment and dereference operators are combined. Let’s examine some examples.

Example 1: ++*ptr

Consider the following code:

int value = 10;
int *ptr = &value;

++*ptr;

Both prefix ++ and dereference * belong to the same precedence level and have right-to-left associativity.

Therefore, the expression is grouped as:

++(*ptr);

First, ptr is dereferenced to identify the object being modified. The prefix increment then increases that object’s value. After the operation:

value == 11;

The pointer itself is not modified.

Example 2: *ptr++

Now consider:

int numbers[] = {10, 20, 30};
int *ptr = numbers;

*ptr++;

Postfix ++ has higher precedence than dereference *. Therefore, the expression is grouped as:

*(ptr++);

The postfix increment produces the original pointer value and advances ptr to the next array element. The dereference accesses the element identified by the original pointer value. However, because the dereferenced value is not used, this expression has no useful effect beyond advancing the pointer.

After the operation, ptr points to numbers[1].

Example 3: (*ptr)++

Compare the previous example with:

int numbers[] = {10, 20, 30};
int *ptr = numbers;

(*ptr)++;

Here, parentheses explicitly group the dereference operation before postfix increment. As a result, the value pointed to by ptr is incremented. After execution:

numbers[0] == 11;

The pointer remains unchanged.

Comparison of Pointer Expressions

ExpressionMeaningWhat changes?
++*ptrIncrement the pointed-to valueValue
(*ptr)++Post-increment the pointed-to valueValue
*ptr++Dereference the original pointer, then advance itPointer
*++ptrAdvance the pointer, then dereference itPointer

These expressions are especially common when iterating through arrays, buffers, and strings.

Operator Precedence vs Order of Evaluation

One of the most important distinctions in C is that operator precedence and evaluation order are not the same thing. Precedence determines how an expression is grouped, but it does not generally determine which operand is evaluated first. Consider:

int result = func1() + func2();

The addition operator requires the results of both function calls, but C does not specify whether func1() or func2() is evaluated first. The compiler may evaluate either function first. This matters when expressions contain side effects, such as modifying variables.

Example of Undefined Behavior

Consider:

int a = 5;
int result = a++ + ++a;

This expression has undefined behavior because a is modified more than once without the required sequencing between those modifications. The compiler is not required to produce any particular result. A safer approach is to separate the operations:

int a = 5;

int first = a++;
int second = ++a;

int result = first + second;

Now the operations are sequenced through separate statements, making the behavior well-defined.

Short-Circuit Evaluation

There are important exceptions where C guarantees evaluation order. For example, the logical AND operator && evaluates its left operand first. If the left operand is false, the right operand is not evaluated.

int *ptr = NULL;

if (ptr != NULL && *ptr > 0) {
    // Safe pointer access
}

Here, *ptr is evaluated only when ptr is not NULL. This behavior is called short-circuit evaluation.

The logical OR operator || behaves similarly, except that it skips its right operand when the left operand is true.

The conditional operator ?: and comma operator also provide sequencing guarantees. Understanding these rules helps prevent subtle bugs, particularly in expressions that modify variables or access hardware.

7. Best Practices for Writing Clear Expressions

Although C allows complex expressions, readability is often more important than minimizing the number of lines of code.

A few practical recommendations:

In embedded systems, these practices can make debugging significantly easier.

Summary

C provides a wide range of operators for performing calculations, manipulating bits, accessing memory, and controlling program logic. Operators can be classified by the number of operands they require: unary, binary, and ternary.

When several operators appear in an expression, precedence determines how they are grouped, while associativity determines grouping between operators of the same precedence level.

However, neither precedence nor associativity generally determines the order in which operands are evaluated. Understanding these distinctions is essential for writing reliable C programs, especially when dealing with pointers, hardware registers, and expressions that modify program state.

Exit mobile version