5

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?

iammilind
  • 68,093
  • 33
  • 169
  • 336

2 Answers2

3

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
-1

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);
}
hygull
  • 8,464
  • 2
  • 43
  • 52
  • What's the meaning of such code? printing `t.a`? Looping only till 3 ? – Ajay May 29 '18 at 11:00
  • It's clear in the code that it's counter's value is true for i=0,1,2. So it is printing 3 times. – hygull May 29 '18 at 11:03
  • `printf("%d\n", t.a);` will always print the address of `t.a` (i.e. `&t.a[0]`) - why loop? – Ajay May 29 '18 at 11:05
  • Sorry **@Ajay**, mistakenly I answered another question's answer here. I will check and change my answer. Thanks. – hygull May 29 '18 at 11:08