简体   繁体   English

在C中重复使用struct是一个好习惯吗?

[英]Is it a good practice to repeatedly use struct in C?

Suppose I have these two structs coming from different header files: 假设我有两个结构来自不同的头文件:

header_1.h header_1.h

struct main_node {
    struct *sec_node
}

header_2.h header_2.h

struct sec_node {
    int var;
}

Now I am using this both header files in main.c and the code looks something like this: 现在我在main.c使用这两个头文件,代码看起来像这样:

#include <stdio.h>
#include "header_1.h"
#include "header_2.h"

struct main_node *node;

void main()
{
  for (int i = 0; i < 1000; i++)
      printf( "%d\n", node->sec_node->var) ;
}

Let's assume, I am not using a modern optimizing compiler. 我们假设,我没有使用现代优化编译器。 I'm looping over this struct many times, would it be faster/good practice to use a temp variable here? 我多次循环这个struct ,在这里使用临时变量会更快/更好吗?

Is there any difference performance-wise in C? 在C中,性能方面有什么不同吗?

void main()
{
   int temp = node->sec_node->var;
   for (int i = 0; i < 1000; i++)
      printf( "%d\n", temp);
}

It's not bad , but it can be a source of optimization bottleneck. 它并不 ,但它可能是优化瓶颈的来源。 Because the compiler cannot see the definitions of external functions (like printf here, although it might know about its properties as a builtin because it's a standard function), it must assume any external function could modify any non- const object whose address it could see. 因为编译器无法看到外部函数的定义(比如printf ,虽然它可能知道它的属性是内置函数,因为它是一个标准函数),但它必须假设任何外部函数都可以修改任何非const对象,它的地址可以看到。 As such, in your example, node or node->sec_node may have a different value before and after the call to the external function. 因此,在您的示例中, nodenode->sec_node在调用外部函数之前和之后可能具有不同的值。

One way to mitigate this is with temps like you're doing, but you can also make use of the restrict keyword as a promise to the compiler that, during the lifetime of the restrict -qualified pointer, the pointed-to object will not be accessed except via pointers "based on" the restrict -qualified one. 缓解这种情况的一种方法是使用像你一样的临时值,但你也可以使用restrict关键字作为编译器的一个承诺,在restrict限定指针的生命周期中,指向对象不会是除了通过指向“基于” restrict指针访问。 How to do this is probably outside the scope of this question. 如何做到这一点可能超出了这个问题的范围。

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

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