HomebaseWorks
Lesson 3 of 4

Operators, integer rules and precedence

Integer division, i++ versus ++i, = inside if, & versus &&, unsigned wraparound and the precedence facts that output questions rely on.

EWritten by the HomebaseWorks editorial team · reviewed 26 Oct 2026

C screenings love short expressions with a printf, because they test whether you know the language's integer rules rather than whether you can type. Every case below is predictable once you know the rule behind it.

Advertisement

Integer arithmetic

When both operands are integers, division drops the fraction and % gives the remainder. Make one operand a floating-point value to get a decimal result.

printf("%d\n", 7 / 2);        /* 3 */
printf("%d\n", -7 / 2);       /* -3, truncation toward zero */
printf("%.1f\n", 7 / 2.0);    /* 3.5 */

unsigned int u = 0;
u = u - 1;
printf("%u\n", u);            /* 4294967295 with a 32-bit unsigned int */
printf("%d\n", -1 < 1u);      /* 0: the -1 is converted to unsigned */

Characters are small integers, so 'A' + 1 is 66 and prints as B with %c. Unsigned values wrap around instead of going negative, and mixing signed with unsigned converts the signed side, which is why -1 < 1u is false.

Increment and assignment

int i = 5;
int a = i++;   /* a = 5, then i becomes 6 */
int b = ++i;   /* i becomes 7, then b = 7 */
printf("%d %d %d\n", a, b, i);   /* 5 7 7 */

int x = 10;
if (x = 0) printf("ran\n");
else printf("x is now %d\n", x);   /* x is now 0 */

i++ returns the old value, ++i the new one. An assignment inside if is legal, evaluates to the assigned value, and is almost always a typo for ==.

Precedence and bitwise versus logical

int flags = 6;                           /* binary 110 */
printf("%d %d\n", flags & 2, flags && 2);   /* 2 1 */
printf("%d\n", 10 > 5 > 2);             /* 0 */

& works bit by bit; && gives 0 or 1 and stops early. 10 > 5 > 2 is evaluated as (10 > 5) > 2, so 1 > 2, which is 0. Comparisons do not chain. Arithmetic binds tighter than comparison, and comparison tighter than &&, so add parentheses whenever you are unsure.

Common mistakes and a practice habit

  • Expecting 7 / 2 to print 3.5.
  • Writing if (x = 0) and wondering why the branch never runs.
  • Using & where && was meant, so a condition like a & b is false when both are nonzero but share no bits.
  • Writing i = i++ or a[i] = i++. These modify i twice without a sequence point and have undefined behaviour, so any "answer" is a guess.

Practice habit: Compile every snippet you study with gcc -Wall -Wextra and treat each warning as a question to answer. Then write three expression-and-printf puzzles of your own each day, predict the output, and run them. Puzzles you set yourself stick far better than ones you only read.

Advertisement
Continue with C4 lessons · 1 interview set · 1 test · 1 certificate
Not tested

More in Programming