0

I can't change variable value outside functions.
this code below throws up an error

#include <stdio.h>
#include <string.h>

struct student{
   unsigned int age:3;
};


struct student student1;
student1.age=8;/*this line*/

int main( ) {

    student1.age = 4;
    printf( "student1.age : %d\n", student1.age );

    student1.age = 7;
    printf( "student1.age : %d\n", student1.age );

    student1.age=5;
    printf( "student1.age : %d\n", student1.age );

    return 0;
}

this doesn't throw error

    #include <stdio.h>
#include <string.h>

struct student{
   unsigned int age:3;
};


struct student student1;
/*student1.age=8;this line*/

int main( ) {

    student1.age = 4;
    printf( "student1.age : %d\n", student1.age );

    student1.age = 7;
    printf( "student1.age : %d\n", student1.age );

    student1.age=5;
    printf( "student1.age : %d\n", student1.age );

    return 0;
}

please explain why. Also, outside a function, it doesn't allow for me to change global variable's value once it's defined.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

2 Answers2

1

An assignment statement can only exist inside a function, so as the system knows when to execute the statement. It's not allowed to reside in a file scope, only can exist in a block scope of a function.

To elaborate, in C (hosted environment) program execution starts from main() function and it ends when it reaches end of main(), or terminated programatically. In a typical environment, the control moves from _start to main(), then child functions, back to main() and finally back to _start for program termination. Thus, any statement residing outside any function block, would not have a chance to execute, rendering it practically useless. That's why run-time statements are not allowed outside a function block.

Initialization, on the other hand, is allowed in file scope. The computation happens at compile time and the initialization happens before the execution of main() - so this can be and is allowed.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

This

student1.student1=6;/*This line*/

is an assignment and need to be include into a function. This means, it's not allowed to change a variable or struct outside a function.
It's only allowed to initialize the struct at global scope.

Mike
  • 4,041
  • 6
  • 20
  • 37