473,563 Members | 2,668 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using const qualifier

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(c onst 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!
Dec 30 '07 #1
5 1975
amvoi...@hushma il.com wrote:
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(c onst 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?
Cast the return value to non-const.
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?
Yes.
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)
This would only be a valid design if 's->pointer' is also const.
If it isn't (and isn't meant to be) remove the const
qualifier against *p.
{
* * s->pointer = p;
}

struct mystruct {
* * int *pointer;
};
--
Peter
Dec 30 '07 #2
On Dec 30, 2:11 am, Peter Nilsson <ai...@acay.com .auwrote:
amvoi...@hushma il.com wrote:
Hi,
My question is about how to useconstproperl y.
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
constqualifiers eems appropriate in the parameter.
So essentially I have:
struct node {
...
struct node *next;
};
struct node *find_special(c onststruct node *n)
{
while (...) {
...
n = n->next;
....
}
return n;
}
But this will give me a warning since I am returning n,
which is declaredconst, and my function is not returning
aconst. How do I fix this?

Cast the return value to non-const.
I knew that was one possible way to silence the warning, but
having read this groups for some time, I had the impression that
casts are almost never necessary. Is this a case where a cast
is perfectly okay?
If I change my function to
return aconst, I would be stuck with a variable which I can
not change when I use my function, right?

Yes.
Also, let's say I have a function that assigns a pointer to a
member of a struct. Here I also think aconstwould do:
void assign_pointer( struct mystruct *s,constint *p)

This would only be a valid design if 's->pointer' is alsoconst.
If it isn't (and isn't meant to be) remove theconstqualifi eragainst *p.
What makes the first example a valid design, but not this one if 's-
>pointer'
is not const? I mean, in respective function the pointers are not
altered
at all, but after the function ends they can be altered. I don't see
the
difference between them. Does a function need to take into account
that a
pointer may be changed after returning from a function?
{
s->pointer = p;
}
struct mystruct {
int *pointer;
};

--
Peter
Thanks!
Dec 30 '07 #3
On 30 Dec, 00:42, amvoi...@hushma il.com wrote:
Hi,
My question is about how to use const properly.
I have two examples describing my problem.
What Peter and Eric have said elsethread is correct, but I think your
conception may be wrong.
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(c onst struct node *n)
{
* * while (...) {
* * * * ...
* * * * n = n->next;
* * * * ....
* * }
* * return n;

}
This function returns a non-const pointer to a node of the list. The
function itself does not modify the list. But it returns a pointer
through which you could modify the list. So your function, having
promised not to modify the list, can't then guarantee that the promise
is kept. This is why you are having problems.
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;

};
Similar problem here. Your function promises that it won't alter the
int that p points to. But it lets "pointer" point to it, and "pointer"
is free to alter the value pointed at.

I think you need to ask yourself the question "Do I want the pointed-
at thing to be alterable, or not?" and arrange your consts
accordingly.

Hope that helps.
Paul.
Dec 30 '07 #4
In article <73************ *************** *******@e25g200 0prg.googlegrou ps.com>
<gw****@aol.com wrote:
>[The node-finding] function returns a non-const pointer to a
node of the list. The function itself does not modify the list.
But it returns a pointer through which you could modify the list.
So your function, having promised not to modify the list, can't
then guarantee that the promise is kept. This is why you are
having problems.
Indeed: given a function that does not modify the object or objects
to which its argument pointer(s) point, but *does* return a pointer
to one of those objects, you have a problem.

Do you use "const" to imply "I will not change this, and thus you
can pass to me a pointer to an actually-const, really-in-ROM object",
and then have the return value "de-const-ified"? In which case,
you can do bad things:

typedef <whateverT;
T *deconstify(con st T *);
const T read_only_obj = { value_that_cann ot_change };
*deconstify(&re ad_only_obj) = oops_a_bug;

Or, do you avoid const, after which you cannot even *call* the
function even though you would have done it safely? For instance:

T *nonconst(T *); /* nonconst() does not modify it though */
const T *ptr;
ptr = nonconst(&read_ only_obj); /* alas, this gets a diagnostic */

The Standard C Library takes the former approach: functions like
strchr() "deconstify " their argument:

const char ro[] = "room!";

*strchr(ro, 'r') = 'b'; /* boom! */

(which may indeed "go boom", i.e., crash, and does on some of my
systems).

One of the many reasons C++ has overloaded functions is to sidestep
this problem. In C++, the types of arguments -- including whether
they are const-qualified -- determine which function is actually
called, so we simply write two completely separate functions:

const int *operate(const int *);
int *operate(int *);

Then:

const int obj1 = 0
int obj2 = 0;

*operate(&obj1) = 42;

will not compile, because &obj1 has type "const int *", so this
calls operate(const int *), which returns "const int *", not
"int *". Of course, this opens the door to abuse: the two
separate functions might well do entirely different things.
Ideally, the const-qualified version of the function does the
same thing as the non-const-qualified version, and in a language
better than C++, we could avoid writing two functions by simply
declaring that the return type matches the argument type:

flexible operate(arg) [
constraint: typeof(operate) is typeof(arg);
constraint: typeof(arg) is choice { int *, const int * };
] {
...
return arg;
}

which also of course lets us write "overloaded " functions without
repeating them six ways from Sunday:

/*
* Substring operation: find "needle" in "haystack"
*/
flexible substring(hayst ack, needle) [
constraint: typeof(operate) is typeof(haystack );
constraint: typeof(needle) is typeof(haystack );
constraint: typeof(haystack ) is choice {
char *, const char *,
Unicode16 *, const Unicode16 *,
Unicode32 *, const Unicode32 *
};
] {
... code to find substring ...
}

(To achieve the above, C++ generally uses "templates" instead of,
or combined with, "overloaded " functions, but there is really
no need for both.)

(I made up the above syntax on the fly, so it is probably full
of flaws.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Dec 30 '07 #5
Chris Torek wrote:

[snip]
Ideally, the const-qualified version of the function does the
same thing as the non-const-qualified version, and in a language
better than C++, we could avoid writing two functions by simply
declaring that the return type matches the argument type:
[snip]
which also of course lets us write "overloaded " functions without
repeating them six ways from Sunday:

/*
* Substring operation: find "needle" in "haystack"
*/
flexible substring(hayst ack, needle) [
constraint: typeof(operate) is typeof(haystack );
constraint: typeof(needle) is typeof(haystack );
Why? What's wrong with allowing substring(L"uni code string", "string")?
constraint: typeof(haystack ) is choice {
char *, const char *,
Unicode16 *, const Unicode16 *,
Unicode32 *, const Unicode32 *
};
] {
... code to find substring ...
}
--
Army1987 (Replace "NOSPAM" with "email")
Jan 2 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3623
by: joe | last post by:
hi, after reading some articles and faq, i want to clarify myself what's correct(conform to standard) and what's not? or what should be correct but it isn't simply because compilers don't support. (first i compiled them with g++3.x. ERR means compiler will bark, otherwise it does accept it. Then the Comeau C/C++ 4.3.3 comes)
13
2478
by: matthias_k | last post by:
Hi, I've never thought about this before, but since you are able to overload a function only by changing the const-ness of the formal parameters, some annoying side effects will arise. For example, if you only have this code ... void foo( const int n ) {}
11
2100
by: x-pander | last post by:
given the code: <file: c.c> typedef int quad_t; void w0(int *r, const quad_t *p) { *r = (*p); }
9
2612
by: sarathy | last post by:
Hi, Can anyone just help me with what exactly is constant expression. I read the section on Constant expression in K&R2. i am not fully clear with it.
10
2766
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
1864
by: d3x0xr | last post by:
Heh, spelled out in black and white even :) Const is useles... do NOT follow the path of considering any data consatant, because in time, you will have references to it that C does not handle, and you'll be left with just noisy compiler warnings and confusion. if you start a project with all char *, and char ** and even char ***, if you...
4
1665
by: junky_fellow | last post by:
Hi guys, Consider the following statements. const int *ptr; /* ie the contents pointed to by ptr cannot be changed */ My question is how/who prevents the contents from being modified ? Is it the C compiler that would give compile time error while trying to change the contents ? Or is it the implementation that would somehow
4
1908
by: =?utf-8?b?QXNiasO4cm4gU8OmYsO4?= | last post by:
Suppose I have a function that takes a pointer as its input, but does not change what the pointer points to. In that case, the const qualifier can be used to indicate that the variable pointed to is not changed. But should this const qualifier be used in the function declaration, the function definition, or both? Example: In .h-file...
1
1596
by: mcbhagyaraj | last post by:
sir, i am getting doubt on const qualifier . Que: void main() { const int f(int ); int b = 4; int a = f(&b); printf("%d", a); // o/p i am getting 4 is it ok or compiler depent and compiled with warnning discarding const qualifier
0
7659
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7882
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8103
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7634
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6244
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5481
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5208
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2079
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.