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);
}
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.
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.
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.
A structure T cannot contain itself.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With