How to create an ASSERT macro to catch assertion failure in C

2 Answers

0 votes
#include <stdio.h>

#define ASSERT(expression)                                      \
    {                                                           \
        if (expression) {                                       \
        } else {                                                \
            assertion_failure(#expression, __FILE__, __LINE__); \
        }                                                       \
    }
    
void assertion_failure(const char* expression, const char* file, int line) {
    printf("Assertion Failure: %s, in file: %s, line: %d\n", expression, file, line);
}    
    
int main(void)
{
    ASSERT(1 == 0);
    
    return 0;
}

 
 
/*
run:

Assertion Failure: 1 == 0, in file: main.c, line: 17
 
*/

 



answered May 28, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

#define ASSERT(expression, message)                                      \
    {                                                                    \
        if (expression) {                                                \
        } else {                                                         \
            assertion_failure(#expression, message, __FILE__, __LINE__); \
        }                                                                \
    }
    
void assertion_failure(const char* expression, const char* message, const char* file, int line) {
    printf("Assertion Failure: %s, message: '%s', in file: %s, line: %d\n", expression, message, file, line);
}    
    
int main(void)
{
    ASSERT(1 == 0, "Your message");
    
    return 0;
}

 
 
/*
run:

Assertion Failure: 1 == 0, message: 'Your message', in file: main.c, line: 18
 
*/

 



answered May 28, 2024 by avibootz

Related questions

6 answers 449 views
1 answer 117 views
117 views asked Sep 23, 2021 by avibootz
1 answer 150 views
1 answer 136 views
136 views asked Jan 8, 2024 by avibootz
2 answers 218 views
1 answer 154 views
...