简体   繁体   中英

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

struct main_node {
    struct *sec_node
}

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:

#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?

Is there any difference performance-wise in 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. As such, in your example, node or node->sec_node may have a different value before and after the call to the external function.

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. How to do this is probably outside the scope of this question.

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