What is purpose of res; in following struct?

208 views Asked by At
struct response {
    string resp[MAXSIZE];
    string type[MAXSIZE];
    int n;
}res;
1

There are 1 answers

1
Vlad from Moscow On

It is a declaration of an object with the name res of the type struct response.

A structure definition can be used as a type specifier similarly like

int res;

but instead of the type int you may place the structure definition

Here is a demonstrative program

#include <iostream>

int main() 
{
    struct Hello
    {
        const char *hello;
        const char *world;
    } hello = { "Hello", "World!" };

    std::cout << hello.hello << ' ' << hello.world << '\n';

    return 0;
}

Its output is

Hello World!

You could write the declaration of the object hello in one line like

struct Hello {  const char *hello; const char *world; } hello = { "Hello", "World!" };

But this is less readable.

In fact it is the same as if to write

    struct Hello
    {
        const char *hello;
        const char *world;
    }; 

    Hello hello = { "Hello", "World!" };
    // or 
    // struct Hello hello = { "Hello", "World!" };