简体   繁体   中英

Assigning structure variable a value

When i assign value to s.rollno in this way it doesnot work

#include<stdio.h>
struct student{
int rollno;
int marks;
}s  ;
s.rollno = 2;

int main(){

printf("%d",s.rollno);

}

BUt if i assign value to s.rollno in main it works

#include<stdio.h>
struct student{
int rollno;
int marks;
}s  ;

int main(){
s.rollno = 2;


printf("%d",s.rollno);

}

you cannot write

 s.rollno = 2;

in global scope, as a separate statement. All the statements needs to appear inside some function , which can execute them.

However, you can initialize the value at the time of definition, like

struct student {
    int rollno;
    int marks;
} s = {.rollno = 2};  

You can create a global variable outside of a function scope like this:

int a;
int main() {
   a = 5;
}

But you cannot set it like you do. This is because of the difference between runtime and compile time. Global variables are created and set to memory and this is determined at compile time. But code like a=5 above is performed at run time. Imagine this situation:

int a;
a = somestruct.somefunction();

Without a function to run this in, how can we be sure what a is? Things done outside the scope of a function cannot occur at run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM