Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #165936

Re: Verbose assert

From Tim Rentsch <tr.17687@z991.linuxsc.com>
Newsgroups comp.lang.c
Subject Re: Verbose assert
Date 2022-04-25 15:41 -0700
Organization A noiseless patient Spider
Message-ID <86h76g6b1z.fsf@linuxsc.com> (permalink)
References <suq3j4$2r5$1@dont-email.me> <bee669c3-c65b-4476-9989-0e1c063c8504n@googlegroups.com> <Gu8QJ.14770$XFM9.1016@fx18.iad> <susovh$qvj$1@dont-email.me> <87r17xafpo.fsf@bsb.me.uk>

Show all headers | View raw


Ben Bacarisse <ben.usenet@bsb.me.uk> writes:

> Mehdi Amini <atorrses@gmail.com> writes:
>
> It seems you want something like this:
>
>   #include <stdio.h>
>   #include <stdarg.h>
>   #include <stdlib.h>
>
>   void my_assert(int cond, const char *fmt, ...)
>   {
>        if (!cond) {
>             va_list al;
>             va_start(al, fmt);
>             vfprintf(stderr, fmt, al);
>             va_end(al);
>             exit(EXIT_FAILURE);
>        }
>   }
>
>   #define MY_ASSERT(cond, fmt, ...) \
>        my_assert(cond, "*** \"%s\" line %d: " fmt, \
>                  __FILE__, __LINE__, __VA_ARGS__)
>
>   int main(void)
>   {
>        int a = 41, b = 42;
>        MY_ASSERT(a == b, "%d != %d as required.\n", a, b);
>   }
>
> Note that this uses string concatenation to build the format, but you
> can write a version that will work with non-literal formats.

Just a few comments on this.

One, the filename and line number can be combined to produce a
single string literal at compile time, using the preprocessor and
"gluing together" of string literals (and which can then be
combined with the format in the same way as above).

Two, usually it's a bad idea in cases like this to expand the
macro into a single function call, because variadic functions
cannot be inlined.

Three, another problem along those lines is that the function
arguments are evaluated even if the tested condition succeeds.
Combining points two and three, we might revise the macro
definition to something like (disclaimer: not tested)

    #define MY_ASSERT( test, ... ) (                          \
      ! (test)                                                \
        ? my_assert_failed( FILE_LINE_STRING() __VA_ARGS__ )  \
        : 0                                                   \
    )

(Note that the format string, if any, is part of __VA_ARGS__
and will be combined with the FILE_LINE_STRING() string per the
rules of combining adjacent string literals.)

Back to comp.lang.c | Previous | Next | Find similar


Thread

Re: Verbose assert Tim Rentsch <tr.17687@z991.linuxsc.com> - 2022-04-25 15:41 -0700

csiph-web