Home > other >  Syntax for pointers to a structure
Syntax for pointers to a structure

Time:02-01

When declaring a pointer to a struct, both the following code snippets compile without error:

A)

struct Foo
{
int data;
Foo* temp;   // line in question
}

B)

struct Foo
{
int data;
struct Foo* temp;  //line in question
}

What is the significance to repeating the word "struct" in the declaration of the struct pointer (as in (B))? Are there any differences compared to not doing so (as in (A))?

Thank you for your consideration.

CodePudding user response:

In C, struct keyword must be used for declaring structure variables, but it is optional in C .

For example, consider the following examples:

struct Foo
{
    int data;
    Foo* temp; // Error in C, struct must be there. Works in C  
};
int main()
{
    Foo a;  // Error in C, struct must be there. Works in C  
    return 0;
}

Example 2

struct Foo
{
    int data;
    struct Foo* temp;   // Works in both C and C  
};
int main()
{
    struct Foo a; // Works in both C and C  
    return 0;
}

In the above examples, temp is a data member that is a pointer to non-const Foo.

  •  Tags:  
  • Related