-1

I created a structure with two elements and tried to assign a value to one of the structure elements outside main function. But I'm getting error while compiling.

#include <stdio.h>
#include <stdlib.h>
struct node{
    char a;
    int b;
};
struct node sr;
sr.b = 48;
int main(){
    printf("Value:%d",sr.b);
    return 0;
}

I'm assigning value after the declaration. Why is this code giving error.

error message

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘.’ token
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
rahul_T_T
  • 133
  • 9

2 Answers2

3

You cannot have a statement which needs runtime execution outside main(), i.e., in file scope. It needs to be present inside some block scope, inside a function so as to determine when to be executed.

You can however, use initialization to have the initial values stored for the members of the structure type variable. Something like

 struct node sr = {'Z', 1};

will initialize sr.a to 'Z' and sr.b to 1. In case you're only interested in initializing member b, you'll be needing designated initializers, like

struct node sr = { .b = 1 };
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Put the following lines inside main() function.

struct node sr;
sr.b = 48;

Why? You cannot have a statement which needs runtime execution outside main(). It needs to be in the scope of a block, for example, inside a function so as to determine when to be executed.

Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • That's true, but OP probably already knows this. – Sourav Ghosh Feb 28 '17 at 17:47
  • 1
    This question is looking for an *explanation*, not simply for working code. Your answer provides no insight for the questioner, and may be deleted. Please [edit] to explain what causes the observed symptoms. – Toby Speight Feb 28 '17 at 17:47