Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      assert

      From cppreference.com
      <cpp‎ |error
       
       
      Diagnostics library
       
      Defined in header<cassert>
      Disabled assertion
      (1)
      #define assert(condition) ((void)0)
      (until C++26)
      #define assert(...)       ((void)0)
      (since C++26)
      Enabled assertion
      (2)
      #define assert(condition) /* unspecified */
      (until C++26)
      #define assert(...)       /* unspecified */
      (since C++26)

      The definition of the macroassert depends on another macro,NDEBUG, which is not defined by the standard library.

      1) IfNDEBUG is defined as a macro name at the point in the source code where<cassert> or<assert.h> is included, the assertion is disabled:assert does nothing.
      2) Otherwise, the assertion is enabled:

      assert checks if its argument (which must have scalar type):

      • If the argument compares unequal to zero, there are no further effects.
      • Otherwise,assert creates a diagnostic on the standard error stream and callsstd::abort().
      (until C++26)

      assert puts a diagnostic test into programs and expands to an expression of typevoid.__VA_ARGS__ is evaluated andcontextually converted tobool:

      • If the evaluation yieldstrue, there are no further effects.
      • Otherwise,assert creates a diagnostic on the standard error stream and callsstd::abort().
      (since C++26)

      The diagnostic information has an implementation-defined format, but it always includes the following information:

      • the text ofcondition
      (until C++26)
      • #__VA_ARGS__
      (since C++26)
      • the source file name (i.e.,__FILE__)
      • the source line number (i.e.,__LINE__)
      • the name of the enclosing function (i.e.,__func__)

      The expressionassert(E) is guaranteed to be aconstant subexpression, if either

      • NDEBUG is defined at the point whereassert is last defined or redefined, or
      • E,contextually converted tobool, is a constant subexpression that evaluates totrue.
      (since C++11)

      Contents

      [edit]Parameters

      condition - expression of scalar type

      [edit]Notes

      Becauseassert is afunction-like macro, commas anywhere in the argument that are not protected by parentheses are interpreted as macro argument separators. Such commas are often found in template argument lists and list-initialization:

      assert(std::is_same_v<int,int>);// error: assert does not take two argumentsassert((std::is_same_v<int,int>));// OK: one argumentstatic_assert(std::is_same_v<int,int>);// OK: not a macro std::complex<double> c;assert(c==std::complex<double>{0,0});// errorassert((c==std::complex<double>{0,0}));// OK
      (until C++26)

      There is no standardized interface to add an additional message toassert errors. A portable way to include one is to use acomma operator provided it has not beenoverloaded, or use&& with a string literal:

      assert(("There are five lights",2+2==5));assert(2+2==5&&"There are five lights");

      The implementation ofassert inMicrosoft CRT does not conform to C++11 and later revisions, because its underlying function (_wassert) takes neither__func__ nor an equivalent replacement.

      Since C++20, the values needed for the diagnostic message can also be obtained fromstd::source_location::current().

      Even though the change ofassert in C23/C++26 is not formally a defect report, the C committeerecommends implementations to backport the change to old modes.

      [edit]Example

      Run this code
      #include <iostream>// uncomment to disable assert()// #define NDEBUG#include <cassert> // Use (void) to silence unused warnings.#define assertm(exp, msg) assert((void(msg), exp)) int main(){    assert(2+2==4);std::cout<<"Checkpoint #1\n";     assert((void("void helps to avoid 'unused value' warning"),2*2==4));std::cout<<"Checkpoint #2\n";     assert((010+010==16)&&"Yet another way to add an assert message");std::cout<<"Checkpoint #3\n";     assertm((2+2)%3==1,"Success");std::cout<<"Checkpoint #4\n";     assertm(2+2==5,"Failed");// assertion failsstd::cout<<"Execution continues past the last assert\n";// No output}

      Possible output:

      Checkpoint #1Checkpoint #2Checkpoint #3Checkpoint #4main.cpp:23: int main(): Assertion `((void)"Failed", 2 + 2 == 5)' failed.Aborted

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 2234C++11assert could not be used in constant expressioncan be used

      [edit]See also

      contract_assert statement(C++26) verifies an internal condition during execution[edit]
      static_assert declaration(C++11) performs compile-time assertion checking[edit]
      causes abnormal program termination (without cleaning up)
      (function)[edit]
      C documentation forassert
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/error/assert&oldid=180999"

      [8]ページ先頭

      ©2009-2025 Movatter.jp