+ 1
Validating values using assert function c++
how can I validate values and then display a message if the value is correct or not using the assert function?
1 Réponse
+ 4
Assert macro in its very nature will emit a descriptive message when fails, but you're still able to add your custom line into the assertion condition by either `&&` (logical AND) or `,` (comma) operators. Since you didn't mention any use case for that, I'd show you the process of validating the macro substitution during
//#define NDEBUG
#include <cassert>
#define SQUARE(b) (b) * (b)
int main() {
int x = 5;
assert (("FAILED" , SQUARE(++x) == 36));
}
In the above fragment, `#define NDEBUG` is a GCC directive to disable the assert macro which is commented out for now.
`#define SQUARE(b) (b) * (b) ` is an unsafe function macro which under certain circumstances produces undefined behaviour so we wanna detect that if it's the case.
`assert (("FAILED" , SQUARE(++x) == 36));` will fail during the evaluation process because of the side effect of the increment operator after macro substitution as
assert ("FAILED" , (++x) * (++x) == 36);
therefore, the output would be like so
" This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
Assertion failed!
Program: ..\Playground\
File: ..\Playground\, Line 8
Expression: ("FAILED" , SQUARE(++x) == 36) "