Difference between revisions of "Assert"
(Created page with "'''<code>assert</code>''' is a function available in the <code>cassert<code> header file that enables immediate termination of a program if an expression evaluates to false....") |
|||
(2 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | '''<code>assert</code>''' is a function available in the <code>cassert<code> header file that enables immediate termination of a program if an expression evaluates to false. It can be used to exit from a program at any point, even inside a function. | + | '''<code>assert</code>''' is a function available in the <code>cassert</code> header file that enables immediate termination of a program if an expression evaluates to false. It can be used to exit from a program at any point, even inside a function. |
<source lang="cpp"> | <source lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
#include <cassert> | #include <cassert> | ||
+ | |||
+ | using namespace std; | ||
int main() | int main() | ||
Line 18: | Line 20: | ||
cout << "Result is: " << numerator / denominator << endl; | cout << "Result is: " << numerator / denominator << endl; | ||
+ | |||
+ | return 0; | ||
} | } | ||
</source> | </source> | ||
− | + | Output: | |
+ | |||
+ | <source lang="shell-script"> | ||
+ | Enter numerator: 5 | ||
+ | Enter denominator: 0 | ||
+ | a.out: assert.cpp:16: int main(): Assertion `denominator != 0' failed. | ||
+ | Aborted | ||
+ | </source> |
Latest revision as of 18:04, 23 January 2018
assert
is a function available in the cassert
header file that enables immediate termination of a program if an expression evaluates to false. It can be used to exit from a program at any point, even inside a function.
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
cout << "Enter numerator: ";
double numerator;
cin >> numerator;
cout << "Enter denominator: ";
double denominator;
cin >> denominator;
assert(denominator != 0);
cout << "Result is: " << numerator / denominator << endl;
return 0;
}
Output:
Enter numerator: 5
Enter denominator: 0
a.out: assert.cpp:16: int main(): Assertion `denominator != 0' failed.
Aborted