简体   繁体   中英

Directly assign value of struct member into variable

I had come across the following code which is very new and interesting.

u8 m_var = stptfunc()->mem;

Never seen these kind of initialization before. The code compiles and run fine. I was just curious if this is a common Practice.

Usually I will code like this...

strtype *ptrfunc()
{
// statements
}

sttype *stvar = ptrfunc();
u8 var = stvar->mem;

Example code:

typedef unsigned char u8;

typedef struct{
    u8 mem;
}sttype;

sttype *stptfunc(void)
{
    static sttype stvar;
    stvar.mem = 255;
    return &stvar;
}

int main()
{
    u8 m_var = stptfunc()->mem;
    printf("value of %d",m_var);
    return 0;
}

output [1]: https://i.stack.imgur.com/rSUaD.png

stptfunc()->mem indicates stptfunc is a function returning a pointer which is being dereferenced to get its mem field. Since we have the entire program we can see this assumption holds up.

This is probably bad practice. What if stptfunc returns NULL ? There is no guarantee it won't.

In such a simple program, it's not a big deal, but it's a bad practice to get into.

Also, as per the comments, the static variable within a function is probably a very poor practice vs. using malloc/free.

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