Deutsch   English   Français   Italiano  
<vcn63s$1n207$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Andrey Tarasevich <andreytarasevich@hotmail.com>
Newsgroups: comp.lang.c
Subject: Re: how to make a macro work as a single line if stmt without braces
Date: Sat, 21 Sep 2024 12:17:15 -0700
Organization: A noiseless patient Spider
Lines: 39
Message-ID: <vcn63s$1n207$1@dont-email.me>
References: <PaWdnZ3R-9zI6nP7nZ2dnZfqn_GdnZ2d@brightview.co.uk>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Sat, 21 Sep 2024 21:17:16 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="babab0d9fc9a6140e9f18085996c0b30";
	logging-data="1804295"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX19oW74IspWmsi9oWv7aJMJl"
User-Agent: Mozilla Thunderbird
Cancel-Lock: sha1:pymIM4LEBGEcWYGscDjOkFEPCzs=
Content-Language: en-US
In-Reply-To: <PaWdnZ3R-9zI6nP7nZ2dnZfqn_GdnZ2d@brightview.co.uk>
Bytes: 2103

On 09/21/24 12:35 AM, Mark Summerfield wrote:
> I have this macro:
> 
> #define WARN(...)                                       \
>      do {                                                \
>          fprintf(stderr, "%s#%d: ", __FILE__, __LINE__); \
>          fprintf(stderr, __VA_ARGS__);                   \
>      } while (0);
> 
> which I use like this:
> 
> total++;
> if (failed) {
>      WARN("failed because...");
> } else
>      ok++;
> 
> I would prefer to be able to write this instead:
> 
> total++;
> if (failed)
>      WARN("failed because...");
> else
>      ok++;
> 
> but doing so results in a compiler error:
> 
> error: 'else' without a previous 'if'

The whole idea of `do { ... } while(false)` idiom for writing complex 
macros is based on _not_ including that `;` after `while(false)` into 
the macro. Meanwhile, you botched the whole thing by adding that `;` there.

Remove the trailing `;` from the macro and everything will work as you 
want it to.

-- 
Best regards,
Andrey