ProgrammingJunior C developer, Embedded developer

Describe how the single-line conditional operator if (without braces) works. When is it safe to use, and what pitfalls exist in its syntax?

Pass interviews with Hintsage AI assistant

Answer.

From the very beginning, the C language allowed omitting curly braces for a single statement within an if statement. This made the code more compact but led to many non-obvious errors, especially when extending and modifying the code. The historical reason is space-saving and simplicity of syntax for minimalist cases.

The problem arises when a developer forgets that without braces, if controls only the first expression following it: all subsequent ones are executed unconditionally, even when this may not be visually apparent. This style leads to hidden bugs that are difficult to identify while reading the code and errors arising from forgotten indentation or added new lines.

The solution is to always use curly braces, even if there is only one statement. This enhances both readability and safety of the code.

Code example:

// Bad: if (x > 0) do_something(); do_other(); // Always executed // Better: if (x > 0) { do_something(); do_other(); }

Key features:

  • Without braces, if controls only the first statement.
  • Indentation does not matter for compilation in C.
  • Adding lines without braces may break the logic.

Tricky Questions.

Does indentation (tab/space) affect the scope of if?

No, in C, the scope is defined only by braces, not by indentation.

What behavior will this code have?

if (a > 0) fun1(); fun2();

fun1() will be called only if a > 0. fun2() will always be called regardless of the condition.

What are the consequences if a new line is added without braces?

This code may change behavior and lead to errors that are visually hard to detect, as indentation does not protect against compilation errors.

Common Mistakes and Anti-Patterns

  • Adding new statements in if without curly braces.
  • Expecting that indentation defines the scope.
  • Non-obvious execution of extra statements.

Real-life Example

Negative Case

A developer added a second statement to a single-line if, forgetting to add braces.

if (user) initialize(); log_access();

Pros:

  • Narrow saving of one line of code.

Cons:

  • Logic error, difficult debugging, leads to security bugs.

Positive Case

A developer always uses curly braces even for a single statement:

if (user) { initialize(); log_access(); }

Pros:

  • Predictability, ease of maintenance, reduced likelihood of error.

Cons:

  • Slight increase in code volume.