Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare several variables in a for (;;) loop in C?

I thought one could declare several variables in a for loop:

for (int i = 0, char* ptr = bam; i < 10; i++) { ... } 

But I just found out that this is not possible. GCC gives the following error:

error: expected unqualified-id before 'char'

Is it really true that you can't declare variables of different types in a for loop?

like image 903
bodacydo Avatar asked Jul 27 '10 23:07

bodacydo


People also ask

Can you declare multiple variables in a for loop?

In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.

Can you declare multiple variables in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can you declare variables in loops C?

There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.


2 Answers

You can (but generally shouldn't) use a local struct type.

for ( struct { int i; char* ptr; } loopy = { 0, bam };       loopy.i < 10 && * loopy.ptr != 0;       ++ loopy.i, ++ loopy.ptr )     { ... } 

Since C++11, you can initialize the individual parts more elegantly, as long as they don't depend on a local variable:

for ( struct { int i = 0; std::string status; } loop;       loop.status != "done"; ++ loop.i )     { ... } 

This is just almost readable enough to really use.


C++17 addresses the problem with structured bindings:

for ( auto [ i, status ] = std::tuple{ 0, ""s }; status != "done"; ++ i ) 
like image 127
Potatoswatter Avatar answered Sep 22 '22 21:09

Potatoswatter


It's true that you can't simultaneously declare and initialize declarators of different types. But this isn't specific to for loops. You'll get an error if you do:

int i = 0, char *ptr = bam; 

too. The first clause of a for loop can be (C99 §6.8.5.3) "a declaration" or a "void expression". Note that you can do:

int i = 0, *j = NULL; for(int i = 0, *j = NULL;;){} 

because i and *j are both of type int. The exact syntax for a declaration is given in §6.7

like image 24
Matthew Flaschen Avatar answered Sep 23 '22 21:09

Matthew Flaschen