Skip to main content

Getting Started with Z3 C++ API

This guide introduces the core concepts and classes of the Z3 C++ API with practical examples.

Basic Concepts

The Z3 C++ API is built around a few key classes:
  • z3::context - Manages all Z3 objects and configuration
  • z3::solver - The satisfiability solver
  • z3::expr - Represents expressions (formulas and terms)
  • z3::sort - Represents types (Bool, Int, Real, etc.)

Your First Z3 Program

Let’s start with a simple satisfiability problem:
Output:

Working with the Context

The z3::context is the foundation of all Z3 operations. Every Z3 object is associated with a context.

Creating Constants

Creating Values

Using the Solver

The z3::solver is used to check satisfiability of formulas.

Basic Solver Operations

Possible Results

The check() method returns one of three values:
  • z3::sat - The constraints are satisfiable
  • z3::unsat - The constraints are unsatisfiable
  • z3::unknown - Z3 could not determine satisfiability

Extracting Models

When a formula is satisfiable, you can extract a model:

Building Expressions

The C++ API provides operator overloading for building expressions naturally.

Boolean Operations

Arithmetic Operations

Comparison Operations

Common Examples

Solving Linear Constraints

Proving a Theorem

To prove a theorem, we check if its negation is unsatisfiable:

Using Push/Pop for Incremental Solving

The solver maintains a stack of assertions:

Working with Bitvectors

Error Handling

The C++ API throws exceptions on errors:

Configuration

You can configure Z3 through the context:

Next Steps