Errors and Assertions

Avoiding Side Effects in Assertions

Is it okay to use assert() with expressions that have side effects, like assert(++x > 0)? Or should assertions be side-effect free?

Abstract art representing computer programming

In general, it's best practice to avoid side effects in assertions. Assertions should be used to check invariants and preconditions, not to modify state or perform logic that affects program behavior.

Here's an example of an assertion with a side effect:

#include <cassert>

void risky_increment(int& x) {
  assert(++x > 0);
}

int main() {
  int a = 0;
  risky_increment(a);
  // What's the value of a here?
}

The problem with this is:

  1. It's not immediately clear that x is being modified by the assertion.
  2. The behavior of the function changes depending on whether assertions are enabled (e.g. in debug vs release builds).

Instead, perform any necessary modifications separately and then assert on the result:

#include <cassert>

void safe_increment(int& x) {
  ++x;
  assert(x > 0);
}

This makes the increment explicit and ensures the function behavior is consistent regardless of assertion settings.

A similar guideline applies to assertions in constructors or destructors. Avoid complex logic or side effects that could leave the object in an indeterminate state if an assertion fails:

class User {
  std::string name;
  int age;
public:
  User(std::string name, int age) : name(name), age(age) {
    assert(age >= 0);
  }
};

Here, if the age assertion fails, the User object will still be constructed with whatever name value was provided. It's cleaner to validate the inputs before performing any initialization.

In summary:

  • Keep assertions side-effect free when possible
  • Perform any complex validation or mutation logic outside of assertions
  • Be mindful of assertions in special member functions to avoid half-initialized or half-destructed states

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved