简体   繁体   English

直接将结构成员的值赋给变量

[英]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 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. stptfunc()->mem表示stptfunc是一个 function 返回一个指针,该指针被取消引用以获取其mem字段。 Since we have the entire program we can see this assumption holds up.由于我们拥有整个程序,我们可以看到这个假设成立。

This is probably bad practice.这可能是不好的做法。 What if stptfunc returns NULL ?如果stptfunc返回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.此外,根据评论,与使用 malloc/free 相比,function 中的 static 变量可能是一个非常糟糕的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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