Path: csiph.com!weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: How About Disallowing Assignments In Expressions? Date: Tue, 13 Feb 2024 16:59:38 -0800 Organization: None to speak of Lines: 58 Message-ID: <87a5o3amit.fsf@nosuchdomain.example.com> References: <87r0hlef8q.fsf@nosuchdomain.example.com> <87sf20o4e2.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain Injection-Info: dont-email.me; posting-host="f0324011426819b9e4b7ac5a3d98873d"; logging-data="2453312"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19C7XFDH2zIF45qj7qJsCb8" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux) Cancel-Lock: sha1:GHmkoy7TVPt6jnxstEMYApHgEqY= sha1:R7jaUoOWgyVN6Z/+wxui3g4oQ+M= Xref: csiph.com comp.lang.c:382451 Janis Papanagnou writes: > On 13.02.2024 17:34, David Brown wrote: >> On 13/02/2024 17:14, Janis Papanagnou wrote: >>> On 11.02.2024 13:57, David Brown wrote: >>>> >>>> [...] They had been trying to rule out "if (x = y)" >>>> and requiring it to be written "x = y; if (x != 0) ...". >>> >>> One could of course also have written it as >>> >>> if (x = y) // this is intentionally an assignment! >>> >>> Sometimes a comment is better than asking to rewrite the code. >>> >> >> That is sometimes the case, but not here. >> >> It is better to write the code clearly than to have a comment explaining >> why you have written code that looks odd. > > Is it odd? - After all it's a common code pattern. > > But, yes. If in doubt you should choose some means to make > it clear. And if it's the separation for you, that's fine. > > Myself I observed me using all three variants (separating, > idiomatic, and commenting), depending on the context. Another option is: if ((x = y)) It's not *inherently* obvious that this is a good idea, but it's the idiom suggested by gcc: "warning: suggest parentheses around assignment used as truth value [-Wparentheses]". Though personally, I'd probably make the assignment the operand of a larger expression. I understand that if (foo) is a common idiom where foo is of any scalar type, but I personally prefer to write one of if (foo != 0) if (foo != '\0') if (foo != 0.0) if (foo != NULL) because I find it clearer (unless foo is of type bool or is otherwise appropriate to use directly as a condition). Thus if x and y are ints, I'd probably write: if ((x = y) != 0) (Assuming I'm not required to follow MISRA rules.) YMMV. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com Working, but not speaking, for Medtronic void Void(void) { Void(); } /* The recursive call of the void */