Lädt...


🔧 Declaring Multiple Variables in a “for” Loop Initialization Clause


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Introduction

As you know, the syntax of the for statement in C and C++ is:

    for ( init-clause ; condition-expr ; iteration-expr )

where:

  • init-clause is used to initialize (prepare for) the start of the loop;
  • condition-expr is evaluated before each iteration: if zero, the loop exits;
  • iteration-expr is evaluated after each iteration.

All are optional; if condition-expr is omitted, it’s as if it were 1, hence:

for (;;) {  // forever
  // ...
}

loops forever (presumably to be exited by one of break, return, goto, exit(), longjmp(), abort(), or in C++, throw).

C++ also has range-based for loops, but that’s a story for another time.

Originally, the init-clause could be only a statement or expression; starting in C99, it could alternatively be a declaration:

for ( unsigned i = 0; i < m; ++i ) {

which is nice because it limits the scope of the variable(s) declared to the loop body. Multiple variables may also be declared:

for ( unsigned i = 0, j = 0; i < m && j < n; ++i, ++j ) {

The iteration-expr may use the comma operator to evaluate more than one sub-expression. (Actually, any expression may use the comma operator to evaluate more than one sub-expression.)

But what if you want to declare more than one variable where the types are different? You can’t. Instead, you’re forced to declare variables of different types outside the loop:

size_t i = 0;
for ( node_t *p = list->head; p->data; ++i, p = p->next ) {

Or so I thought. As I commented:

Even in a relatively small language like C, I’m still learning new techniques even though I’ve been using C for over 35 years.

It turns out you can declare more than one variable where the types are different in the init-clause.

The Trick

The trick is to use a local, anonymous struct:

for ( struct { size_t i; node_t *p; } loop = { 0, list->head };
      p->data; ++loop.i, loop.p = loop.p->next ) {

Of course, you can name loop anything you want; iter or it are reasonable alternatives.

Granted, it looks weird and it’s somewhat ugly to have to refer to loop — but you can do it. One place it’s likely more useful is if the loop is part of a macro where the ugliness would be hidden.

But just because you can do it, should you? That’s debatable. After all, it’s not so terrible that variables of different types are declared outside the loop. It’s a trade-off with how important it is that all the variables are limited to the scope of the loop. In C, this typically isn’t that important.

In C++, however, if at least one of the loop variables is of a type that has a destructor and it’s important that it runs as soon as the loop terminates, then that might justify the use of the struct. Of course C++ has structured bindings that can be used instead:

for ( auto [i, p] = std::make_tuple( 0, list->head );
      p->data; ++i, p = p->next ) {

Conclusion

The struct trick certainly isn’t that significant, perhaps not even enough to justify the existence of this article. But I do think it’s clever and perhaps even useful in limited cases, so I thought it worth passing on since I’ve never encountered it in over 35 years of programming in C.

...

🔧 Declaring Multiple Variables in a “for” Loop Initialization Clause


📈 94.46 Punkte
🔧 Programmierung

🔧 Declaring Variables in Golang


📈 41.24 Punkte
🔧 Programmierung

🕵️ CVE-2023-29537 | Mozilla Firefox up to 111 Font Initialization initialization (Bug 1823365)


📈 30.82 Punkte
🕵️ Sicherheitslücken

🕵️ tpm2-tss up to 2.4.2/3.0.0 Initialization initialization


📈 30.82 Punkte
🕵️ Sicherheitslücken

🔧 Refactoring instance variables to local variables in Rails controllers


📈 28.28 Punkte
🔧 Programmierung

🔧 Semantic elements, Semantic elements in HTML, HTML style guide and declaring document types


📈 27.1 Punkte
🔧 Programmierung

📰 New Zealand Uber Drivers Win Landmark Case Declaring Them Employees


📈 27.1 Punkte
📰 IT Security Nachrichten

📰 Declaring a Climate Emergency Won’t Save the Planet — Energy Security Could


📈 27.1 Punkte
📰 IT Security Nachrichten

🕵️ Since declaring cyber war on Russia Anonymous leaked 5.8 TB of Russian data


📈 27.1 Punkte
🕵️ Hacking

📰 Declaring State of Emergency, Samoa Makes Measles Vaccinations Compulsory


📈 27.1 Punkte
📰 IT Security Nachrichten

📰 Prominent Pro-Patent Judge Issues Opinion Declaring All Software Patents Bad


📈 27.1 Punkte
📰 IT Security

📰 US finds no cyber threats, despite declaring "national emergency"


📈 27.1 Punkte
📰 IT Security Nachrichten

📰 Prominent Pro-Patent Judge Issues Opinion Declaring All Software Patents Bad


📈 27.1 Punkte
📰 IT Security

📰 US finds no cyber threats, despite declaring "national emergency"


📈 27.1 Punkte
📰 IT Security Nachrichten

🔧 C# | Avoid Multiple Nested If-Else Statements Using Guard Clause


📈 26.78 Punkte
🔧 Programmierung

📰 The Loop Kodi Addon: How to Install Loop for Kodi


📈 22.06 Punkte
🖥️ Betriebssysteme

🪟 What is the new ‘Board visualization’ for Loop Tables in Microsoft Loop?


📈 22.06 Punkte
🪟 Windows Tipps

📰 (g+) Microsoft Loop im Test: Mit Loop-Elementen zur besseren Zusammenarbeit


📈 22.06 Punkte
📰 IT Nachrichten

📰 Microsoft Loop: Was genau ist die Loop Komponente?


📈 22.06 Punkte
🖥️ Betriebssysteme

🕵️ QEMU 5.0.0 TD List hw/usb/hcd-ohci.c Infinite Loop infinite loop


📈 22.06 Punkte
🕵️ Sicherheitslücken

📰 Chase Bank Is Quietly Adding a Forced Arbitration Clause To Some Credit Cards


📈 20.73 Punkte
📰 IT Security Nachrichten

🐧 What if the De-facto FLOSS license was standard BSD with one extra clause?


📈 20.73 Punkte
🐧 Linux Tipps

📰 Ärger um den Einsatz der Commons Clause


📈 20.73 Punkte
📰 IT Nachrichten

📰 DIB Orgs – Here’s How Your ISO 9001 Performance Evaluation Clause Helps with CMMC


📈 20.73 Punkte
📰 IT Security Nachrichten

🔧 Understanding OVER() Clause in SQL


📈 20.73 Punkte
🔧 Programmierung

🐧 The Commons Clause will destroy open source


📈 20.73 Punkte
🐧 Linux Tipps

📰 DIB Orgs – Here’s How Your ISO 9001 Improvement Clause Helps with CMMC


📈 20.73 Punkte
📰 IT Security Nachrichten

🔧 Python Trick: The else Clause on Loops


📈 20.73 Punkte
🔧 Programmierung

🐧 [$] Redis modules and the Commons Clause


📈 20.73 Punkte
🐧 Linux Tipps

📰 DIB Orgs – Here’s How Your ISO 9001 Operation Clause Helps with CMMC


📈 20.73 Punkte
📰 IT Security Nachrichten

📰 Google Removes 'Don't Be Evil' Clause From Its Code of Conduct


📈 20.73 Punkte
📰 IT Security Nachrichten

matomo