Search code examples
c++assertassertionsstatic-assert

use of assert and static assert functions


I am trying to understand the use of static_assert and assert and what the difference is between them, however there are very little sources/explantions about this

here is some code

// ConsoleApplication3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "conio.h"
#include "cassert"
#include "iostream"


int main()
{
    assert(2+2==4);
    std::cout << "Execution continues past the first assert\n";
    assert(2+2==5);
    std::cout << "Execution continues past the second assert\n";
    _getch();
}

comments on redundency will be appreciated(since I am learning "how to c++")

output in cmd

Execution continues past the first assert
Assertion failed: 2+2==5, file c:\users\charles\documents\visual studio 2012\pro
jects\consoleapplication3\consoleapplication3\consoleapplication3.cpp, line 14

I have been trying to find out the different mehtods and uses of it, but as far as I understand it is a runtime check and another "type" of if statement

could someone just clarify the use and explain what each one does and they difference?


Solution

  • You can think of assertions as sanity checks. You know that some condition should be true unless you've screwed something up, so the assertion should pass. If you have indeed screwed something up, the assertion will fail and you'll be told that something is wrong. It's just there to ensure the validity of your code.

    A static_assert can be used when the condition is a constant expression. This basically means that the compiler is able to evaluate the assertion before the program ever actually runs. You will be alerted that a static_assert has failed at compile-time, whereas a normal assert will only fail at run time. In your example, you could have used a static_assert, because the expressions 2+2==4 and 2+2==5 are both constant expressions.

    static_asserts are useful for checking compile-time constructs such as template parameters. For example, you could assert that a given template argument T must be a POD type with something like:

    static_assert(std::is_pod<T>::value, "T must be a POD type");
    

    Note that you generally only want run-time assertions to be checked during debugging, so you can disable assert by #defineing NDEBUG.