Why can I not put statements into class scope?

81 views Asked by At
#include<stdio.h>
#include<stdlib.h>
struct Node
{
    int val;
    struct Node *link;
    (*link).val = 12; // error
};

int main()
{
    struct Node *link=(struct Node*)malloc(sizeof(struct Node));
    (*link).val = 15; // OK
    return 0;
}

Why am I getting an error when trying to access (*link).val inside the struct, while the same thing is working just fine in the main function?

1

There are 1 answers

0
Vlad from Moscow On

You may declare members of a structure but you may not use statements (in C++ there can be declaration statements) within a structure declaration in C and C++ like for example that

(*link).val=12;

A structure declaration may contain only declarations.

And in C opposite to C++ even member declarations may not have initializers. That is you may not write in C

struct Node
{
    int val = 12;
    struct Node *link;
};

Pay attention to that this code snippet

struct Node *link;
(*link).val=15;

invokes undefined behavior because the pointer link is uninitialized and has an indeterminate value.

Instead you could write for example

struct Node node;
struct Node *link = &node;
(*link).val=15;