58

I saw somewhere assert used with a message in the following way:

assert(("message", condition));

This seems to work great, except that gcc throws the following warning:

warning: left-hand operand of comma expression has no effect

How can I stop the warning?

Alexandru
  • 25,070
  • 18
  • 69
  • 78
  • See [this](http://stackoverflow.com/questions/5665611/why-does-this-code-produce-a-warning-referring-to-the-comma-operator) related question. – razlebe May 03 '11 at 10:00

9 Answers9

96

Use -Wno-unused-value to stop the warning; (the option -Wall includes -Wunused-value).

I think even better is to use another method, like

assert(condition && "message");
pmg
  • 106,608
  • 13
  • 126
  • 198
  • 11
    Nice one, I usually do assert(condition /* message */). – Julien Jan 22 '13 at 08:22
  • This sometimes gives "Conditional expression is constant" warning in Visual Studio. Any ideas on how to remove the warning without suppressing it? – Samaursa Apr 04 '13 at 23:56
  • @Samaursa: you probably have an issue with plain `condition`. Does the compiler also warn with just `assert(condition);`? – pmg Apr 05 '13 at 09:35
  • It does not. The interesting thing is that OP's original problem code is the solution to VS's warnings! `assert((Msg, Cond));` works without warnings on VS 2008. – Samaursa Apr 05 '13 at 19:58
  • `assert(() && "msg");` causes CppCheck (v1.90) to generate an "incorrectStringBooleanError" warning. – ahogen Dec 04 '19 at 22:35
24

Try:

#define assert__(x) for ( ; !(x) ; assert(x) )

use as such:

assert__(x) {
    printf("assertion will fail\n"); 
}

Will execute the block only when assert fails.

IMPORTANT NOTE: This method will evaluate expression x twice, in case x evaluates to false! (First time, when the for loop is checking its condition; second time, when the assert is evaluating the passed expression!)

Peter Varo
  • 11,726
  • 7
  • 55
  • 77
bugfeeder
  • 349
  • 2
  • 2
  • 4
    The nice thing about this is that you can omit the message if you want by using `assert__(foo);` and the semicolon will end the block. – Kevin Cox Jun 10 '14 at 14:29
  • 2
    Such implementation will not work if `(x)` returns true only once: `string("a") a; assert__(a.append("b") == "ab") { ... }` – Oleg Nov 27 '15 at 14:34
  • 3
    Why `for` and not `if`? – Caridorc Jan 03 '16 at 22:10
  • This does not seem to work in GCC. Failing `assert` stops the program execution and `printf` is not called. – VLL May 20 '21 at 12:04
  • @vil It is not possible for `assert` to stop the program before `printf` because `assert` is not called until after `printf`. – Jack G Oct 22 '21 at 22:11
13

If you want to pass a formatted message, you could use the following macros:

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_error(M, ...) fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define assertf(A, M, ...) if(!(A)) {log_error(M, ##__VA_ARGS__); assert(A); }

Then use it like printf:

// With no args
assertf(self != NULL,"[Server] Failed to create server.");

// With formatting args
assertf((self->socket = u_open(self->port)) != -1,"[Server] Failed to bind to port %i:",self->port);
// etc...

Output:

[ERROR] (../src/webserver.c:180: errno: Address already in use) [Server] Failed to bind to port 8080: webserver: ../src/webserver.c:180: server_run: Assertion `(self->socket = u_open(self->port)) != -1' failed.

Based on http://c.learncodethehardway.org/book/ex20.html

frmdstryr
  • 20,142
  • 3
  • 38
  • 32
  • This, unfortunately, isn't portable. C99 requires that you use at least one of the optional arguments in a variadic macro (e.g this: `assertf(x == y, "x does not equal y")` violates the standard. This is easily rectified via `assertf(x == y, "%s", "x does not equal y")` however). It also relies on the gcc extension `##__VA_ARGS__` which isn't necessarily a bad thing, but it does make it less portable – chad Sep 14 '15 at 17:49
2

By tradition, (void) communicates to the compiler that you are knowingly ignoring an expression:

/* picard.c, TNG S6E11. */
#define assertmsg(x, msg) assert(((void) msg, x))
assertmsg(2+2==5, "There! are! four! lights!");
Mingye Wang
  • 1,107
  • 9
  • 32
2

For unexpected default case of a switch, an options is

assert(!"message");
Flaviu
  • 931
  • 11
  • 16
0

A function that takes const char* and returns true would probably save you from all sorts of warnings:

#include <assert.h>

int always_true(const char *msg) {
    return 1;
}

#define assert_msg(expr, msg) assert((expr) && always_true(msg))
JiaHao Xu
  • 2,452
  • 16
  • 31
0

In my case, I changed @pmg's answer to be able to control the output. The (... && "message") didn't work for me.

#include <assert.h>
#include <stdio.h>

#define __DEBUG__ 1

assert ((1 == 1) && 
       (__DEBUG__ && printf("  - debug: check, ok.\n")) || !__DEBUG__);
user9869932
  • 6,571
  • 3
  • 55
  • 49
  • Try `NDEBUG` instead of `__DEBUG__`. It's the standard way to do this as defining `NDEBUG` automatically disables all `asset`s. – Jack G Aug 15 '22 at 18:13
-1

You could write your own macro that provides the same usage of _Static_assert(expr, msg):

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>


/*
 * void assert_msg(bool expr, const char *msg);
 */
#if !defined(NDEBUG)
#define assert_msg(expr, msg)   do                  \
{                                                   \
        const bool  e_ = expr;                      \
                                                    \
        if (!e_) {                                  \
                fputs(msg, stderr);                 \
                fputc('\n', stderr);                \
                assert(e_);                         \
        }                                           \
} while (0)
#else
#define assert_msg(expr, msg)   do                  \
{                                                   \
                                                    \
        if (!(expr))                                \
                warn_bug(msg);                      \
} while (0)
#endif

I also have a macro warn_bug() that prints the name of the program, the file, the line, the function, the errno value and string, and a user message, even if asserts are disabled. The reason behind it is that it won't break the program, but it will warn that a bug will probably be present. You could just define assert_msg to be empty if defined(NDEBUG), though.

-11

According to following link http://www.cplusplus.com/reference/clibrary/cassert/assert/

assert is expecting only expression. May be you are using some overloaded function.

According to this, only expression is allowed and thus you are getting this warning.

Dhiraj
  • 5
  • 1