'const Struct parameter in C
I'm studying simple binary tree.
I saw a model answer and had a question.
In this code Item and Tree are structs.
typedef struct {
char characters[20];
char name[20];
} Item;
typedef struct node {
Item item;
struct node* left;
struct node* right;
} Node;
typedef struct tree {
Node* root;
int size;
} Tree;
And I'll show two function prototypes.
bool InTree(const Item* pi, const Tree* ptree);
Item* TreeSearch(Tree* ptree, const Item key);
One is using Item* and the other is using Item by parameter. I know what each means. But when const is used, I think there is no difference between these two. If we assumed the memory is big enough.
const Item* pi and const Item key which is better when used as a parameter for a function?
Is it about coding style problem or is it intended?
Solution 1:[1]
/* 1 */ void foo(Item *pi)
/* 2 */ void foo(const Item *pi)
/* 3 */ void foo(const Item * const pi)
All three will pass the reference to the struct, not the struct itself. The difference is :
- the pointer
piand the referenced struct can be modified - the pointer
pican be modified, the referenced struct cannot be modified - the pointer
piand the referenced struct cannot be modified
/* 1 */ void foo(Item pi)
/* 2 */ void foo(const Item pi)
In both cases struct will be copied by value ie the whole struct will be passed to the function. If you modify the member it will not affect the original struct.
- struct
pican be modified - struct
picannot be modified
Solution 2:[2]
Between these two approaches of declarations of parameters with the specifier Item
bool InTree(const Item* pi, const Tree* ptree);
Item* TreeSearch(Tree* ptree, const Item key);
the approach with declaration the parameter like const Item* pi is more preferable compared with the declaration const Item key because in the second case the whole object of the structure type that contains character arrays is copied instead of coping only a pointer to the object that is more efficient.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0___________ |
| Solution 2 | Vlad from Moscow |
