[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <CAHk-=wgRr_D8CB-D9Kg-c=EHreAsk5SqXPwr9Y7k9sA6cWXJ6w@mail.gmail.com>
Date: Wed, 23 Feb 2022 12:22:08 -0800
From: Linus Torvalds <torvalds@...ux-foundation.org>
To: Jakob <jakobkoschel@...il.com>
Cc: Jason Gunthorpe <jgg@...pe.ca>,
Linux Kernel Mailing List <linux-kernel@...r.kernel.org>,
linux-arch <linux-arch@...r.kernel.org>,
Greg Kroah-Hartman <gregkh@...uxfoundation.org>,
Thomas Gleixner <tglx@...utronix.de>,
Arnd Bergman <arnd@...db.de>,
Andy Shevchenko <andriy.shevchenko@...ux.intel.com>,
Andrew Morton <akpm@...ux-foundation.org>,
Kees Cook <keescook@...omium.org>,
Mike Rapoport <rppt@...nel.org>,
"Gustavo A. R. Silva" <gustavo@...eddedor.com>,
Brian Johannesmeyer <bjohannesmeyer@...il.com>,
Cristiano Giuffrida <c.giuffrida@...nl>,
"Bos, H.J." <h.j.bos@...nl>
Subject: Re: [RFC PATCH 04/13] vfio/mdev: remove the usage of the list
iterator after the loop
On Wed, Feb 23, 2022 at 12:15 PM Jakob <jakobkoschel@...il.com> wrote:
>
> in such a case you would still have to set the iterator value to
> NULL when reaching the terminating condition or am I missing something?
No.
Make the rule be "you never use the iterator outside the loop".
IOW, the code sequence is
some_struct *ptr, *iter;
ptr = NULL;
list_for_each_entry(iter, ...) {
if (iter_matches_condition(iter)) {
ptr = iter;
break;
}
}
.. never use 'iter' here - you use 'ptr' and check it for NULL ..
See? Same number of variables as using a separate 'bool found' flag,
but simpler code, and it matches the rule of 'don't use iter outside
the loop'.
This is how you'd have to do it anyway if we start using a C99 style
'declare iter _in_ the loop' model.
And as mentioned, it actually tends to lead to better code, since the
code outside the loop only has one variable live, not two.
Of course, compilers can do a lot of optimizations, so a 'found'
variable can be made to generate good code too - if the compiler just
tracks it and notices, and turns the 'break' into a 'goto found', and
the fallthrough into the 'goto not_found'.
So 'better code generation' is debatable, but even if the compiler can
do as good a job with a separate 'bool' variable and some cleverness,
I think we should strive for code where we make it easy for the
compiler to DTRT - and where the generated code is easier to match up
with what we wrote.
Linus
Powered by blists - more mailing lists