skip to content

In C++, why does `std::cout << flags & 0x0F;` fail to compile, and what does `flags & ACK == ACK` silently test?

level: middleimportance: should knowfreq 50%

answer

  1. grammar fixes the shape first
  2. overloads keep built-in precedence
  3. shift above &, equality above &
  4. bool promotes to int 1

basics

~20 s

An overloaded << keeps the shift operator's precedence, above &, so the line parses as (std::cout << flags) & 0x0F and no & accepts a stream. == binds tighter than &, so flags & ACK == ACK tests flags & 1.

solid answer

~40 s

Precedence comes from the grammar, and an overloaded operator keeps the built-in operator's precedence and associativity. Shift binds tighter than `&`, so `std::cout << flags & 0x0F` means `(std::cout << flags) & 0x0F`; the left operand of `&` is a stream and nothing matches. Equality binds tighter than every bitwise operator, so `flags & ACK == ACK` means `flags & (ACK == ACK)`: the comparison yields `true`, integral promotion makes it `1`, and the expression tests the lowest bit instead of the ACK bit. The same rule makes `std::cout << ok ? "yes" : "no"` print `1`, and `1u << n + 1` shift by `n + 1`. Parenthesize: Clang warns by default, and GCC's `-Wparentheses`, enabled by `-Wall`, targets the same confusions.

code

cpp · 19 lines
cpp
#include <cstdint>
#include <iostream>

int main() {
    std::uint8_t flags = 0x12;             // ACK bit (0x10) set, low bit clear
    constexpr std::uint8_t ACK = 0x10;

    bool wrong = flags & ACK == ACK;       // flags & (ACK == ACK) -> flags & 1
    bool right = (flags & ACK) == ACK;
    std::cout << wrong << ' ' << right << '\n';   // 0 1

    unsigned n = 3;
    unsigned a = 1u << n + 1;              // 1u << (n + 1) == 16
    unsigned b = (1u << n) + 1;            // 9
    std::cout << a << ' ' << b << '\n';           // 16 9

    // std::cout << flags & 0x0F;          // error: invalid operands to binary expression
    std::cout << (flags & 0x0F) << '\n';          // 2
}

go deeper

for a junior

Recall the two surprising rows: equality binds tighter than &, ^ and |, and shifts bind looser than + and -.

for a middle

Explain that parsing happens before overload resolution, so stream << keeps shift precedence, and trace why a == result becomes the int 1.

for a senior

Turn on the parentheses warnings as errors in parser code and read each one as a real bug report, not noise.

for a principal

Set a team rule that mixed bitwise, comparison and shift expressions are always parenthesized, enforced by the compiler rather than by reviewers.

## Precedence is fixed by the grammar C++ has no precedence table in the standard; the order is encoded in the **expression grammar**: a `shift-expression` is built from `additive-expression`s, a `relational-expression` from shift expressions, and so on. Read top to bottom, the binary operators bind in this order (tightest first): | Level | Operators | Groups | |---|---|---| | multiplicative | `*` `/` `%` | left to right | | additive | `+` `-` | left to right | | shift | `<<` `>>` | left to right | | three-way comparison (C++20) | `<=>` | left to right | | relational | `<` `<=` `>` `>=` | left to right | | equality | `==` `!=` | left to right | | bitwise AND, XOR, OR | `&`, then `^`, then `|` | left to right | | logical AND, OR | `&&`, then `||` | left to right | | conditional and assignment | `?:` `=` `+=` ... | right to left | The surprises are the rows where intuition disagrees with the grammar: the **bitwise operators sit below equality**, and **shifts sit below `+` and `-`**. ## Overloading never changes precedence `std::cout << x` calls an overloaded `operator<<`, but the parser decides the shape of the expression before overload resolution ever runs. An overloaded operator keeps the **precedence, associativity and number of operands** of the built-in one. Three consequences show up in header-parsing code: - `std::cout << flags & 0x0F;` parses as `(std::cout << flags) & 0x0F`. The left operand of `&` is a `std::ostream`, no `operator&` accepts it, and the line fails to compile with "invalid operands to binary expression". - `std::cout << ok ? "yes" : "no";` parses as `(std::cout << ok) ? "yes" : "no"`. It compiles, because a stream converts contextually to `bool` in a condition, and prints `1` instead of `yes`. - `std::cout << (flags & 0x0F)` and `std::cout << (ok ? "yes" : "no")` are the fixes: parentheses around anything below shift level. ## The `&` versus `==` trap in C++ `flags & ACK == ACK` parses as `flags & (ACK == ACK)`. In C++ the comparison yields a `bool` (`true`), which **integral promotion** turns into the `int` `1` before `&` runs, so the expression tests the lowest bit of `flags`, not the ACK bit. It compiles silently in the type system; only a diagnostic catches it. The fix is `(flags & ACK) == ACK`, or `(flags & ACK) != 0` for a one-bit mask. ## Shifts below addition `1u << n + 1` is `1u << (n + 1)`, not `(1u << n) + 1`. A packed-field extractor such as `hdr >> 4 & 0x0F` happens to be right (`(hdr >> 4) & 0x0F`) because shift binds tighter than `&`, while `hdr & 0xF0 >> 4` is `hdr & (0xF0 >> 4)`, i.e. `hdr & 0x0F`, which reads the wrong nibble. ## Associativity, the other half Precedence decides which operator wins between two different levels; **associativity** decides how a chain of operators from the same level groups. Almost every binary operator groups left to right, so `a - b - c` is `(a - b) - c` and `hdr >> 4 >> 2` is `(hdr >> 4) >> 2`. Stream chains depend on exactly this: `std::cout << a << b` is `(std::cout << a) << b`, and it works only because each `operator<<` returns the stream it was given, which becomes the left operand of the next one. Assignment and `?:` group right to left, which is why `a = b = 0` assigns `0` to `b` first and then `b`'s new value to `a`. ## What the compilers tell you Compilers diagnose these shapes: - Apple clang 21 warns **by default** with `-Wparentheses` ("& has lower precedence than ==; == will be evaluated first", and "operator '?:' has lower precedence than '<<'") and with `-Wshift-op-parentheses` for `<<` mixed with `+`; - GCC documents `-Wparentheses` as warning "when operators are nested whose precedence people often get confused about", and enables it with `-Wall`; - treating these warnings as errors in a parser library is cheap insurance, because every one of them flags code whose meaning differs from how it reads. ## A habit that scales 1. Parenthesize any expression that mixes bitwise operators with comparisons, shifts with arithmetic, or `&&` with `||`. 2. Parenthesize anything below shift level that you stream with `<<`. 3. Prefer named helpers (`has_flag(flags, ACK)`) over repeating mask expressions inline.

  • Why does `std::cout << ok ? "yes" : "no";` compile and print `1`?
    The conditional operator binds more loosely than `<<`, so the statement is `(std::cout << ok) ? "yes" : "no"`. Streaming `ok` prints `1`; the stream is then used as the condition, which is allowed because a stream converts contextually to `bool`, and the chosen string literal is discarded. Write `std::cout << (ok ? "yes" : "no")`.
  • Can a library give its overloaded `operator<<` a lower precedence to avoid this?
    No. Precedence, associativity and arity belong to the grammar, which is applied before overload resolution, so every `operator<<` parses exactly like the built-in shift. A library can only avoid the trap by choosing a different interface, such as a function call or a format string.

  • An overloaded operator<< for streams has its own, lower precedence.
  • flags & ACK == ACK tests whether the ACK bit is set.
  • Bitwise & binds tighter than == because it is an arithmetic operator.
  • 1u << n + 1 computes (1u << n) + 1.
  • A precedence mistake always shows up as a compile error.