WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Intermediate · question 40 of 100

Explain the difference between ’assert’ and ’static_assert’ in C++. When should you use each?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

assert and static_assert are two C++ language constructs that are used for testing and validation.

The assert macro is used to test a condition during runtime and halt the program if the condition is false. The assert macro is defined in the <cassert> header file, and takes a single argument, which is the condition to test. If the condition is false, the program will terminate and an error message will be printed to the console.

For example:

    #include <cassert>
    
    int main() {
        int x = 0;
        
        assert(x > 0);
        
        return 0;
    }

In this example, we use the assert macro to test whether x is greater than 0. Since x is equal to 0, the condition is false and the program will terminate with an error message.

The static_assert keyword is used to test a condition during compilation time, rather than runtime. The static_assert keyword is defined in the <cassert> header file, and takes two arguments: the condition to test and an optional error message to display if the condition is false.

For example:

    #include <cassert>
    
    template <typename T>
    void foo(T x) {
        static_assert(std::is_integral<T>::value, "T must be an integral type.");
        
        // ...
    }
    
    int main() {
        foo(10);
        //foo(3.14);  // Compile-time error: static assertion failed
        
        return 0;
    }

In this example, we define a function foo that takes a template parameter T. We use the static_assert keyword to test whether T is an integral type, and display an error message if it is not. This allows us to catch errors at compile-time, rather than runtime.

In general, you should use assert to test conditions that are expected to be true at runtime, and static_assert to test conditions that are expected to be true at compile-time. assert is useful for catching runtime errors, while static_assert is useful for catching programming errors and ensuring that your code is correct at compile-time.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics