简体   繁体   中英

Accessing global structs in C functions

My understanding is that C functions only work with copies of variables unless passed by address. However, the following appears to work OK, and I am confused as to why. I am accessing a global struct in a function and it appears to change the global value even though I am not passing the address.

Global struct:
cal{
int a;
int b;
}cal;

Function:
AlterCalAandCalB()
{
cal.a = 1;
cal.b = 2;
}

This appears to change the global variable not just inside function.

I rewrote the code to this, and the performance is identical:

AlterCalAandCalB(struct cal *ptrCal)
{
ptrCal->a = 1;
ptrCal->b = 2;
}

I am interested in learning the best practice, not just what works. I realize that global variables are not recommended but in this particular case it works for me. But I want to learn the best practice for pointers.

My understanding is that C functions only work with copies of variables unless passed by address.

That's slightly confused. C functions receive their arguments by value -- roughly speaking, they receive copies, including if the argument is the address of an object or function. This is about argument passing, not about the behavior of the statements in function bodies.

Every executable statement is inside a function body. There would be no point to "global" variables if functions could not share access to them.

I am interested in learning the best practice, not just what works.

Best practice is a matter of opinion, so it is off topic here. But note that if you are going to pass the address of an object to all functions that you want to access it (excluding main() , I suppose), then there is no point to declaring that object at file scope in the first place.

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