A
amvoiepd
Hi,
My question is about how to use const properly.
I have two examples describing my problem.
First, let's say I have a linked list and from it I want to
find some special node. I write the function, and then figure
that the function will not be modifying the list at all, so a
const qualifier seems appropriate in the parameter.
So essentially I have:
struct node {
...
struct node *next;
};
struct node *find_special(const struct node *n)
{
while (...) {
...
n = n->next;
....
}
return n;
}
But this will give me a warning since I am returning n,
which is declared const, and my function is not returning
a const. How do I fix this? If I change my function to
return a const, I would be stuck with a variable which I can
not change when I use my function, right?
Also, let's say I have a function that assigns a pointer to a
member of a struct. Here I also think a const would do:
void assign_pointer(struct mystruct *s, const int *p)
{
s->pointer = p;
}
struct mystruct {
int *pointer;
};
Same problem here, I'm assigning a const to a non const.
What to do? I can't add const to my struct member, since
I want to do things with it later.
So how do I use const properly? I do understand the reason
why these examples fail, just not how to handle it.
Thanks!
My question is about how to use const properly.
I have two examples describing my problem.
First, let's say I have a linked list and from it I want to
find some special node. I write the function, and then figure
that the function will not be modifying the list at all, so a
const qualifier seems appropriate in the parameter.
So essentially I have:
struct node {
...
struct node *next;
};
struct node *find_special(const struct node *n)
{
while (...) {
...
n = n->next;
....
}
return n;
}
But this will give me a warning since I am returning n,
which is declared const, and my function is not returning
a const. How do I fix this? If I change my function to
return a const, I would be stuck with a variable which I can
not change when I use my function, right?
Also, let's say I have a function that assigns a pointer to a
member of a struct. Here I also think a const would do:
void assign_pointer(struct mystruct *s, const int *p)
{
s->pointer = p;
}
struct mystruct {
int *pointer;
};
Same problem here, I'm assigning a const to a non const.
What to do? I can't add const to my struct member, since
I want to do things with it later.
So how do I use const properly? I do understand the reason
why these examples fail, just not how to handle it.
Thanks!