|
|
Subscribe / Log in / New account

Key Rust concepts for the kernel

Key Rust concepts for the kernel

Posted Sep 27, 2021 23:13 UTC (Mon) by nybble41 (subscriber, #55106)
In reply to: Key Rust concepts for the kernel by Wol
Parent article: Key Rust concepts for the kernel

> What's important (and this is where FORTRAN/Fortran failed), is that the test should be carried out where the test is written.

The context is C code compiled by GCC and Clang. C doesn't have any issue with the placement of the test. A while loop puts the test at the top of the loop, and evaluates it at the top of the loop (before the first iteration of the loop body). The do/while loop places the test at the bottom and evaluates it after executing the body of the loop.

However, if you use a while loop in a context where it would be *incorrect* (as in: results in reading from uninitialized variables) to exit the loop before the body had executed at least once, there is a bug in your code, or at least the very strong *potential* for one even if you think you know that the inputs will always cause the body to be executed. In the absence of some clear human- and machine-readable indication of the initial condition, such as assert() statements, the compiler or other static analysis tool should warn about the potentially uninitialized variable(s). Even with assert() statements I would consider it better to use do/while since it better reflects the actual flow control vs. "assert(expr); while (expr) { ... }" which has the false appearance of a test and branch prior to the first iteration which will (hopefully) be removed by the compiler as dead code.

Or you could structure the code so that it reliably does the right thing even if the initial condition results in the body of the loop not being executed. That would be ideal: easier to read and reason about, while handling a wider range of inputs without risking undefined behavior.


to post comments


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds