What are C Operator Precedence Basics- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

C Operator Precedence Basics

Why 2 + 3 * 5 is 17 and not 25, how precedence and associativity decide evaluation, and the bitmask and shift bugs that bite embedded programmers. Part of the free C programming course.

Operator precedence in C decides which operator acts first when an expression contains more than one. Get it wrong and a perfectly compiled program does the wrong thing, which is why every free C programming course has to cover it before anything complex. In this lesson you will learn what precedence and associativity mean, see them measured with real output, and meet the three mistakes that account for most precedence bugs in embedded C programming.

This free C tutorial lesson introduces the idea and the main groups of operators. The complete level-by-level table follows in the next part of this chapter. Here we focus on understanding, so that when you meet the table you already know what it is for.

What You Will Learn

  • Why a language needs rules for operator precedence in C at all
  • How precedence (which operator first) differs from associativity (which direction for equal operators)
  • A compact ranking of the operator groups you use every day
  • How to prove precedence with a small test program
  • The bitmask, shift and ternary pitfalls to avoid
  • Why precedence does not tell you the order in which operands are evaluated

Prerequisites

  • The arithmetic, relational, logical and bitwise operators from earlier in this chapter
  • GCC on a Linux terminal

Why Operator Precedence in C Exists

Consider 2 + 3 * 5. There are two operators, addition and multiplication. If the addition happens first the answer is 25. If the multiplication happens first the answer is 17. Both readings are mathematically possible, so the language must pick one, and it picks the one you learned at school: multiplication first.

C groups its operators into levels. Each level has a precedence. When an expression has more than one operator, the one with the higher precedence is applied first. Textbooks number the levels from 1, the highest, down to 15, the lowest. Multiplication sits at a higher level than addition, so in the example above the multiplication happens first.

How 2 + 3 * 5 is evaluated

3 * 5 = 15  →  2 + 15 = 17
Parentheses override: (2 + 3) * 5  →  5 * 5 = 25

Precedence Versus Associativity

Precedence compares different operators. It says nothing about two operators from the same level, such as the two subtractions in 10 - 4 - 3. That is the job of associativity, which says whether operators at the same level group from left to right or from right to left.

  • Most binary operators (+ - * / % << >> < > == != & ^ | && ||) associate left to right. So 10 - 4 - 3 means (10 - 4) - 3.
  • Assignment operators, the conditional operator ?: and unary operators associate right to left. So a = b = c means a = (b = c).

Remember the pair as a unit. Precedence picks the winner between different operators, and associativity breaks ties between equal ones.

A Compact Ranking of Common Operators

The full table is next. For now, this ranking covers the operators you will use daily, from highest to lowest precedence:

Level (approx.)OperatorsAssociativity
1Function call (), array index [], member access . ->, postfix ++ --Left to right
2Unary: ! ~ + - ++ -- * & sizeof and the cast (type)Right to left
3* / %Left to right
4+ -Left to right
5<< >>Left to right
6< <= > >=Left to right
7== !=Left to right
8 to 10Bitwise &, then ^, then |Left to right
11 and 12Logical &&, then ||Left to right
13Conditional ?:Right to left
14Assignment = += -= ...Right to left
15Comma ,Left to right

Rough strength of operator groups (strongest first)

Postfix and call
↓
Unary and cast
↓
* / % + – shifts
↓
comparisons bitwise && ||
↓
?: assignment comma

Proving It With a Program

Do not just believe the table. Compile this program and compare the output with your own predictions before you read on.

#include <stdio.h>

int main(void)
{
    int a, b, c;

    printf("2 + 3 * 5        = %d\n", 2 + 3 * 5);
    printf("(2 + 3) * 5      = %d\n", (2 + 3) * 5);
    printf("100 / 10 / 2     = %d\n", 100 / 10 / 2);
    printf("100 / (10 / 2)   = %d\n", 100 / (10 / 2));
    printf("10 - 4 - 3       = %d\n", 10 - 4 - 3);
    printf("1 << 2 + 1       = %d\n", 1 << 2 + 1);
    printf("(1 << 2) + 1     = %d\n", (1 << 2) + 1);

    a = b = c = 7;
    printf("a = b = c = 7 -> a=%d b=%d c=%d\n", a, b, c);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o prec_basic prec_basic.c
$ ./prec_basic
2 + 3 * 5        = 17
(2 + 3) * 5      = 25
100 / 10 / 2     = 5
100 / (10 / 2)   = 20
10 - 4 - 3       = 3
1 << 2 + 1       = 8
(1 << 2) + 1     = 5
a = b = c = 7 -> a=7 b=7 c=7

The sample compiler also complained about the shift line. Notice the warning text, because it is the same one you will see in your own projects:

prec_basic.c:12:41: warning: suggest parentheses around '+' inside '<<' [-Wparentheses]

Reading the results:

  • 2 + 3 * 5 is 17 and (2 + 3) * 5 is 25. Parentheses always override the default order.
  • 100 / 10 / 2 is 5 because division associates left to right, giving (100 / 10) / 2. With the parentheses moved it becomes 20.
  • 10 - 4 - 3 is 3, not 9, for the same reason.
  • 1 << 2 + 1 is 8, not 5. Addition has higher precedence than the shift, so this is 1 << (2 + 1).
  • a = b = c = 7 sets all three variables to 7, because assignment groups from right to left.

The Bitmask Comparison Bug

The most damaging precedence mistake in firmware is testing a bit with & and == in the same expression. The comparison operators sit above the bitwise operators, which surprises almost everyone.

#include <stdio.h>

#define READY_BIT 0x04

int main(void)
{
    unsigned int status = 0x06;

    if (status & READY_BIT == READY_BIT)
        puts("wrong form  : ready");
    else
        puts("wrong form  : NOT ready");

    if ((status & READY_BIT) == READY_BIT)
        puts("right form  : ready");
    else
        puts("right form  : NOT ready");

    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o prec_mask prec_mask.c
$ ./prec_mask
wrong form  : NOT ready
right form  : ready

The register value 0x06 has the ready bit (0x04) set, yet the first test reports not ready. The expression status & READY_BIT == READY_BIT is parsed as status & (READY_BIT == READY_BIT). The comparison yields 1, and 0x06 & 1 is 0, which is false. The second form, with explicit parentheses, is correct. GCC flags the first with a -Wparentheses warning: suggest parentheses around comparison in operand of ‘&’.

Always bracket bitwise tests

Write (reg & MASK) == MASK or (reg & MASK) != 0. This is one of the most common precedence bugs in driver code, and parentheses cost nothing at run time.

Precedence Is Not Evaluation Order

A last subtlety. Precedence tells you how an expression is grouped. It does not tell you in which order the operands are evaluated. In most cases it makes no difference, but when the operands are function calls with side effects, the order is unspecified.

#include <stdio.h>

static int trace(int id)
{
    printf("trace(%d) called\n", id);
    return id;
}

int main(void)
{
    int sum = trace(1) + trace(2) * trace(3);
    printf("sum = %d\n", sum);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o prec_order prec_order.c
$ ./prec_order
trace(1) called
trace(2) called
trace(3) called
sum = 7

The grouping is certain: the multiplication is performed before the addition, so the result is 1 + 2 * 3 = 7. But the order of the three trace calls is not guaranteed by the standard. This GCC run happened to call them left to right, another compiler or a different optimisation level may not. Never write code that depends on it. The same reasoning makes statements such as i = i++ + 1 undefined behaviour, because the variable is modified and read without a defined sequence.

Real-World Uses of Operator Precedence in C

  • Register access: combining shifts, masks and comparisons to read fields from peripheral registers.
  • Pointer code: *p++ means *(p++), because postfix increment outranks dereference. It reads the byte and then advances the pointer.
  • Integer math: 7 / 2 * 2 is 6 but 7 * 2 / 2 is 7. Left-to-right grouping of equal-level operators changes integer results.
  • Conditions: a && b || c groups as (a && b) || c, because && outranks ||.

Common Mistakes and Troubleshooting

MistakeWhat C actually doesFix
x & 1 == 0x & (1 == 0), always 0(x & 1) == 0
1 << n + 11 << (n + 1)(1 << n) + 1 if that is what you meant
if (x = 5)Assigns 5, then tests it (always true)if (x == 5), and enable -Wparentheses
y = x > 3 ? 1 : 2 + zTernary result is 1 or 2 + zUse parentheses around each branch
Relying on the order of function calls in one expressionOrder is unspecifiedStore each result in its own statement

Best Practices for Operator Precedence in C

  • Do not memorise the table, use parentheses. Explicit grouping is easier to read, and coding standards such as MISRA C ask for the precedence of operators to be made explicit.
  • Always parenthesise when you mix bitwise, shift, comparison and logical operators in one expression.
  • Break long expressions into several statements with named temporaries.
  • Compile with -Wall -Wextra so the compiler suggests parentheses where it sees ambiguity.

Performance: parentheses and temporaries do not slow the program. The compiler generates the same code, and the optimiser removes redundant temporaries. Security: a mis-grouped bounds check, such as a length comparison combined with an arithmetic expression, can leave a hole that passes review because it looks right at a glance.

Summary and Key Takeaways

  • Precedence decides which operator is applied first. Higher levels bind tighter.
  • Associativity decides the direction for operators of equal precedence: left to right for most, right to left for assignment, ?: and unary operators.
  • Comparison operators outrank bitwise operators, and addition outranks shifts.
  • Parentheses always win and cost nothing.
  • Precedence is about grouping, not about the order operands are evaluated.

Conclusion

Operator precedence in C is a small set of rules that every expression you ever write depends on. You have seen the reason for the rules, the difference between precedence and associativity, a compact ranking of the operators you use most, and the real bugs that come from forgetting them. In the next part of this free embedded C course you will study the complete precedence and associativity table, and you will be able to read it as a tool you understand instead of a chart to memorise.

Interview Questions on Operator Precedence

What is the result of 2 + 3 * 5 and why?

17, because multiplication has higher precedence than addition and is evaluated first.

What is the difference between precedence and associativity?

Precedence ranks different operators. Associativity decides the grouping direction for operators of the same precedence level.

Why is if (flags & MASK == MASK) a bug?

The equality operator has higher precedence than bitwise AND, so it is parsed as flags & (MASK == MASK).

Frequently Asked Questions

What is operator precedence in C?

It is the set of rules that decides which operator is applied first when an expression contains several operators.

What is associativity in C?

Associativity decides whether operators of the same precedence level are grouped from left to right or from right to left.

Does precedence control the order of evaluation?

No. It controls grouping only. The order in which operands such as function calls are evaluated is mostly unspecified.

Which has higher precedence in C, == or &?

The equality operator == has higher precedence than bitwise &, so bitmask tests need parentheses.

Should I memorise the whole precedence table?

It helps to know the main groups, but writing parentheses is safer and clearer, and many coding standards recommend it.

Where can I find the full table in this free C programming course?

The complete table with associativity for every operator follows in the next part of this chapter.

Keep Going With the Free C Programming Course

Every lesson is free, written for students, and built around programs you can compile and run on any Linux machine. Move on to the next lecture or return to the course index to pick your own path.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →