Assert examples
From NEOSYS Dev Wiki
// main1.cpp - demonstrates standard usage of asserts
#include <iostream>
#include <cassert>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert( x == 4); // aborts here with message "Assertion failed: x == 4, file main1.cpp, line 7
return x;
}
// main2.cpp - demonstrates how to avoid aborting a program
#include <iostream>
#include <cassert_warn>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert( x == 4); // print "Assertion failed: x == 4, file main.cpp, line 7
return x; // ... and immediately returns successfully
}
// main3.cpp - demonstrates how to avoid aborting a program
#include <iostream>
#include <cassert_pause>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert( x == 4); // print "Assertion failed: x == 4, file main.cpp, line 7
return x; // print "Press any key to continue ..." and waits for keypress
}
// main4.cpp - demonstrates how to modify asserts on per statement basis
#include <iostream>
#include <cassert_exodus>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert( x == 4); // aborts here with message "Assertion failed: x == 4, file main1.cpp, line 7
return x;
}
// main5.cpp - demonstrates how to modify asserts on per statement basis
#include <iostream>
#include <cassert_exodus>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert_warn( x == 4); // print "Assertion failed: x == 4, file main.cpp, line 7
return x; // ... and immediately returns successfully
}
// main6.cpp - demonstrates how to modify asserts on per statement basis
#include <iostream>
#include <cassert_exodus>
int main() {
int x = 3;
cout << "Hello, world !\n";
assert_pause( x == 4); // print "Assertion failed: x == 4, file main.cpp, line 7
return x; // print "Press any key to continue ..." and waits for keypress
}