C 堆栈使用临时结构 [英] C stack usage with temporary structures

查看:26
本文介绍了C 堆栈使用临时结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用嵌入式的东西,所以,我为 MCU 使用特殊的 C 编译器 C30.我对它与临时结构的行为感到困惑.

I work with embedded stuff, so, I use special C compiler C30 for MCUs. I'm confused about its behavior with temporary structures.

但是,也许我不知道某些事情,这是预期的行为?

But, maybe I don't know something, and it's intended behavior?

考虑小代码:

typedef struct {
   int a;
   int b;
} T_TestStruct1;

void test1(T_TestStruct1 *p_test_struct)
{
   /* do something */
}

这些对 test1() 的调用:

void some_function()
{

   {
      T_TestStruct1 par = {
         .a = 1,
         .b = 1,
      };
      test1(&par);
   }

   {
      T_TestStruct1 par = {
         .a = 2,
         .b = 2,
      };
      test1(&par);
   }

}

这里一切正常:只有一个 T_TestStruct1 实例被分配到堆栈中.但我喜欢使用较短的表达方式:

Everything is OK here: just one instance of T_TestStruct1 is allocated in the stack. But I like to use shorter expressions:

void some_function()
{
   test1(&(T_TestStruct1){
      .a = 1,
      .b = 1,
      });

   test1(&(T_TestStruct1){
      .a = 2,
      .b = 2,
      });
}

那么,{.a = 1, .b = 1}{.a = 2, .b = 2} 两个结构体都被分配到栈中.但是,在我看来,它们不应该是.实际只需要一个实例.

Then, both structures {.a = 1, .b = 1} and {.a = 2, .b = 2} are allocated in the stack. But, in my opninion, they should not be. Only one instance is actually needed.

碰巧,我试过了:

void some_function()
{
   {
      test1(&(T_TestStruct1){
         .a = 1,
         .b = 1,
         });
   }

   {
      test1(&(T_TestStruct1){
         .a = 2,
         .b = 2,
         });
   }
}

结果是一样的.

那么,这是有意为之,还是编译器中的错误?

So, is it intended behavor, or is it a bug in the compiler?

推荐答案

其实我看不出这个表达式给你带来麻烦的好处.它使代码的可读性降低.

Actually I don't see the benefit of the expression causing you troubles. It makes the code just less readable.

但除此之外:您无法预测编译器是否会创建包含该结构的两个实例的堆栈帧.这取决于编译器和他的优化引擎.如果您真的需要控制此处的内存分配并且您确实需要优化,我建议您分配一次该变量,并在两次调用中明确重用它,并留下评论为什么要这样做.

But apart from that: You can't predict whether the compiler creates a stackframes including two instances of the structure or not. This is up to the compiler and his optimization engine. In case you really need control about the allocation of memory here and you really need to optimize, I'd suggest to allocate this variable once and explicitly reuse it for both calls, leaving a comment why you do it like this.

这篇关于C 堆栈使用临时结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆