简体   繁体   中英

Unnamed struct declaration inside for loop initialization statement

In one of the SO thread, I had seen a usage of unnamed struct acting as a placeholder for multiple variables of different types inside for loop:

For example:

for(struct {
      int i;
      double d;
      char c;
    } obj = { 1, 2.2, 'c' };
    obj.i < 10;
    ++obj.i)
{
  ...
}

This compiles fine with g++.
Is this a standard C++03 syntax?

You can use an unnamed struct anywhere you can use a struct - the only difference is that it doesn't get a name that can be used somewhere else. You can declare a new type anywhere you can use a type, pretty much. It may not be particularly meaningful to do so in most places, but that's another matter.

I wouldn't exactly recommend this, other than in very special cases, but it's valid.

Below code will work in C++ (g++ 5.4.0).

http://rextester.com/ELWLF59792

//g++  5.4.0

#include <iostream>

#include <stdio.h>

int main()
{
      int i = 0;

      for(struct st{ int a[9]; }t;i<3;i++)
            printf("%d\n", t.a);
}

And below code will work in C (gcc 5.4.0).

//gcc 5.4.0

#include <stdio.h>

int main()
{
      int i = 0;
      struct st{ int a[9]; }t;
      for(;i<3;i++)
            printf("%d\n", t.a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM