Home > Enterprise >  How to declare multiple different type variables in one line in C language
How to declare multiple different type variables in one line in C language

Time:02-04

For example:

int a, float b;

But it's wrong.

Actually, I want to use it in the for loop. Just like this:

for (int a, float b; a < 1; a  )
{
        
}

I can use for loops to simplify mutex like this

#define in_mutex_env(val) for(int __x = ({mutex_lock(); 0}); __x < 1; __x  , mutex_unlock())

/* Lock automatically when we enter and unlock automatically when we leave */
in_mutex_env {
    // do something
}

But what's different this time is that I want to declare a variable at the beginning of the for loop and use it in curly braces.

And the reason for this requirement is that I want to use for loops to implement macros like this.

#define to_set_value(val) for(int __x = 0, float val; __x < 1; __x  )

int main(int argc, char *argv[])
{
    /* The for loop must be executed only once */
    to_set_value(myvalue) {
        /* And I must can use local variables of the for loop in curly braces */
        myvalue = 12; 
    }

    /* The macro is expanded into */
    for(int __x = 0, float myvalue; __x < 1; __x  ) {
        myvalue = 12; 
    }

    /* But this is still wrong, just because we can't declare like this */
    int a, float b;

    /* If I put the declare in curly braces, it can no longer be used in the curly braces of the for loop */
    for(int __x = ({float myvalue; 0}), float val; __x < 1; __x  ) {
        myvalue = 12; 
    }
    
    return 0;
}

In fact, I don't have to use for loops, but the question is how to implement similar macros.

CodePudding user response:

C does not provide a way to declare multiple objects of different base types in the first clause of a for statement, but you can declare a structure with different types of members:

#include <stdio.h>

int main(void)
{
    for (struct { int i; float f; } s = {1, 1}; s.i < 10;   s.i)
        printf("%d! = %g.\n", s.i, s.f *= s.i);
}

Clang complains about this, with “declaration of non-local variable in 'for' loop”. It seems it does not like the declaration of a structure type in the for loop, likely due to a strict interpretation of C 2018 6.8.5 3. You can work around it by declaring the structure in advance:

    struct foo { int i; float f; };
    for (struct foo s = {1, 1}; s.i < 10;   s.i)
        printf("%d! = %g.\n", s.i, s.f *= s.i);

Generally you should avoid complicating code like this without good reason.

Also, you should avoid using names that start with two underscores, as those are reserved for the use of the C implementation. If you need to separate names used in macros from names used in your other source code, you should create a different naming convention.

  •  Tags:  
  • c
  • Related