Search code examples
cinitializationvariable-assignment

Why is it that I can't assign values to member variable of structures outside functions?


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.


Solution

  • 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.