Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 427
Sedmaister Avatar asked Oct 05 '18 16:10

Sedmaister


People also ask

When should I use struct in C?

You can use it to store variables in different types. The struct type is comparable to classes in object-oriented programming. Sometimes you may need to assign values to objects with the same properties. Instead of creating multiple variables for these objects in your C program, you can define them in a struct.

Why should I use struct instead of class?

Structs copy the entire value on the assignment, whereas reference types copy the reference on assignment. So, large reference type assignments are cheaper than the value types. Instance field declarations in Struct cannot include variable initializers. But, static fields in Struct can include variable initializers.

When would you use a struct?

Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. 5) A struct is a value type. If you assign a struct to a new variable, the new variable will contain a copy of the original.

Can a struct have itself?

A structure T cannot contain itself.


1 Answers

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.

like image 122
R.. GitHub STOP HELPING ICE Avatar answered Sep 24 '22 01:09

R.. GitHub STOP HELPING ICE