473,385 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

to const or not to const

What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?
Mar 19 '06 #1
8 2637

"Laurijssen" <se***@n.tk> wrote in message
news:dv**********@news4.zwoll1.ov.home.nl...
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?
Declaring the return value as 'const' won't buy you
anything, since what gets returned is a copy of it,
i.e. the caller can still change it.

const int f()
{
return 42;
}

void g()
{
int i = f();
i = 99; /* changes 'i' (the returned object with
value 42 gets destroyed before 'f()'
returns) */
}
The declaration of a 'const int' parameter might be
useful, might not. It will disallow changing the
parameter inside the function, but does not affect
the caller, since the argument is a copy of the caller's
argument.

int f(const int x)
{
x = 42; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
int i = 42;
f(i); /* 'i' is not const, but the copy
of it passed to 'f()' may not
be modified inside scope of 'f()'. */
}

=====================

int f(int x)
{
x = 42; /* ok, but has no effect on caller's argument */
}

void g()
{
int i = 0;
f(i);
/* here, 'i' still has value 0 */
}

==========================

The parameter 'const float *f' means that what the
pointer 'f' points to may not be modified. Since in
this case 'f' will point to a caller's argument, this
protects the caller's argument from changes.

int f(const float *f)
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */

f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */

}

So, if and when to use 'const' depends upon your needs.

-Mike


Mar 19 '06 #2

"Laurijssen" <se***@n.tk> wrote in message
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?

Not really.
If a pointer is const qualified, then you cannot mofdify what it points to.
This has a marginal use in tagging parameters as input rather than output.
However there are various weaknesses in C's implementation of const which
make in not especially useful. For instance members of a const-qulaified
structure can point to writeable memory, and const qualified parameters can
be aliased by writable pointers.

My own opinion is that const hasn't really improved the language, and is
best minimised.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $6.90 paper, available www.lulu.com
Mar 19 '06 #3
Declaring the return value as 'const' won't buy you
anything, since what gets returned is a copy of it,
i.e. the caller can still change it.

const int f()
{
return 42;
}

void g()
{
int i = f();
i = 99; /* changes 'i' (the returned object with
value 42 gets destroyed before 'f()'
returns) */
}
The declaration of a 'const int' parameter might be
useful, might not. It will disallow changing the
parameter inside the function, but does not affect
the caller, since the argument is a copy of the caller's
argument.

int f(const int x)
{
x = 42; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
int i = 42;
f(i); /* 'i' is not const, but the copy
of it passed to 'f()' may not
be modified inside scope of 'f()'. */
}

=====================

int f(int x)
{
x = 42; /* ok, but has no effect on caller's argument */
}

void g()
{
int i = 0;
f(i);
/* here, 'i' still has value 0 */
}

==========================

The parameter 'const float *f' means that what the
pointer 'f' points to may not be modified. Since in
this case 'f' will point to a caller's argument, this
protects the caller's argument from changes.

int f(const float *f)
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */

f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */

}

So, if and when to use 'const' depends upon your needs.

-Mike

Hmm.... maybe my compiler is retarded, but the only way I can duplicate
what you say is when I go like:

#include <stdio.h>

int f(const int *f) {
*f = 2;
return 0;
}

int main(void) {
int n = 100;

/* Using (int*) makes the warning message "warning: passing arg 1 of
'f' makes pointer from integer without a cast." disappear */

f((int*)100);

return 0;
}

Then I compile this under the gnu compiler using the -Werror option (or
flag?).

Chad

Mar 19 '06 #4
Mike Wahler wrote:
"Laurijssen" <se***@n.tk> wrote in message
news:dv**********@news4.zwoll1.ov.home.nl...
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?

<snip> Declaring the return value as 'const' won't buy you
anything, since what gets returned is a copy of it,
i.e. the caller can still change it.

const int f()
{
return 42;
}

void g()
{
int i = f();
i = 99; /* changes 'i' (the returned object with
value 42 gets destroyed before 'f()'
returns) */
That would be impossible, since then 'i' would not be properly initialized.
What happens here is that the value of the expression 'f()' is computed as
42. This value is then assigned to 'i', and then the subsequent assignment
assigns 99 to 'i'.

In fact, execution of f() does not involve any objects.

<snip> The parameter 'const float *f' means that what the
pointer 'f' points to may not be modified. Since in
this case 'f' will point to a caller's argument, this
protects the caller's argument from changes.

int f(const float *f)
It doesn't really matter here, but in general you should of course never
give an argument the same name as the function it belongs to. It's legal,
however.
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */

f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */

}

You seem to be confusing pointers with references here (which C of course
lacks). This code will not compile regardless of 'const', since you're
trying to pass floats as pointers. You mean something like this instead:

void f(float* n) {
*n = 0; /* OK: can modify what 'n' points to */
n = 0; /* OK: can modify 'n' as well, but this has no effect on the
caller */
}

void fc(const float* n) {
*n = 0; /* error: 'n' points to const object, cannot modify */
n = 0; /* OK: can still modify 'n' */
}

void fcc(const float* const n) {
*n = 0; /* error: 'n' points to const object, cannot modify */
n = 0; /* error: 'n' is a const object, cannot modify */
}

void g() {
float n = 42;
f(&n); /* OK: 'n' becomes 0 */
fc(&n); /* OK: convert float* to const float*, 'n' will not be modified */
f(&100); /* error: cannot take the address of a constant */
fc(&100); /* ditto */
}

In C++, one has references which do work in much the way you described, but
of course that's a horse of a different color.

S.
Mar 19 '06 #5
Skarmander wrote:
Mike Wahler wrote:

<snip>
int f(const float *f)


It doesn't really matter here, but in general you should of course never
give an argument the same name as the function it belongs to.


That should be 'parameter', not 'argument'.
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */

f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */

}

You seem to be confusing pointers with references here (which C of
course lacks). This code will not compile regardless of 'const', since
you're trying to pass floats as pointers.

<snip>

The first call is trying to pass an int as a pointer, of course.

S.
Mar 19 '06 #6
> "Laurijssen" <se***@n.tk> wrote in message
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?

In the case of f, yes; in the case of x, not a great one.

Malcolm wrote: Not really.
If a pointer is const qualified, then you cannot mofdify what it points to.
True, but the OP has not given an example of a const qualified pointer.
Consider...

void foo(double * const dcp, const double *cdp)

....where dcp is a const qualified pointer, and cdp is the more usual
pointer to a const qualified object (double).
This has a marginal use in tagging parameters as input rather than output.
I can only recall one perenial clc poster actually recommending that.
It's a style
issue and quite debatable. Those who use it are in a minority (but not
necessarily
wrong to do so.)
However there are various weaknesses in C's implementation of const which
make in not especially useful. For instance members of a const-qulaified
structure can point to writeable memory,
Why should the const-ness of the pointer affect the const-ness of the
memory being pointed to? That is the question the C committee faced,
and their decision that const should be indepentantly applicable to
both the pointer and the contents being pointed to is a natural one.

Note, you can have const pointers to const qualified objects. The
problem is
one of const poisoning, and C's lack of implicit conversion to const
beyond
the first pointer reference.
and const qualified parameters can be aliased by writable pointers.

My own opinion is that const hasn't really improved the language, and is
best minimised.


Like register and volatile, the const keywork is entirely optional to
strictly
conforming programs, assuming you leave the declarations of standard
library functions to the include headers.

So, it hasn't _harmed_ the language. But const can, and quite often is,
used to prevent accidental modification of an object that shouldn't be
modified (at least within a local space like a given function block.)

Const poisoning is difficult to remove from any language, but the fact
that
so many languages do have the notion of const is indicative that it is
a useful construct, even if no one has necessarily found the most
perfect
implementation of it.

--
Peter

Mar 19 '06 #7
Malcolm wrote:
"Laurijssen" <se***@n.tk> wrote in message
What are the advantages of using const as often as possible in C?
Does it help to declare integer function arguments as const? How about
pointers and automatic const integers?

const int func(const int x, const float *f)
{
const int retval = x;

return retval;
}

has it any use to declare these as const?


Not really.
If a pointer is const qualified, then you cannot mofdify what it points to.
This has a marginal use in tagging parameters as input rather than output.
However there are various weaknesses in C's implementation of const which
make in not especially useful. For instance members of a const-qulaified
structure can point to writeable memory, and const qualified parameters can
be aliased by writable pointers.

My own opinion is that const hasn't really improved the language, and is
best minimised.


Use of const char* over char* is to be promoted in my opinion, just to
prevent accidental attempts to modify string literals.

--
Ian Collins.
Mar 19 '06 #8

"Chad" <cd*****@gmail.com> wrote in message
news:11**********************@z34g2000cwc.googlegr oups.com...
Declaring the return value as 'const' won't buy you
anything, since what gets returned is a copy of it,
i.e. the caller can still change it.

const int f()
{
return 42;
}

void g()
{
int i = f();
i = 99; /* changes 'i' (the returned object with
value 42 gets destroyed before 'f()'
returns) */
}
The declaration of a 'const int' parameter might be
useful, might not. It will disallow changing the
parameter inside the function, but does not affect
the caller, since the argument is a copy of the caller's
argument.

int f(const int x)
{
x = 42; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
int i = 42;
f(i); /* 'i' is not const, but the copy
of it passed to 'f()' may not
be modified inside scope of 'f()'. */
}

=====================

int f(int x)
{
x = 42; /* ok, but has no effect on caller's argument */
}

void g()
{
int i = 0;
f(i);
/* here, 'i' still has value 0 */
}

==========================

The parameter 'const float *f' means that what the
pointer 'f' points to may not be modified. Since in
this case 'f' will point to a caller's argument, this
protects the caller's argument from changes.

int f(const float *f)
{
*f = 0; /* error: compiler must issue diagnostic */
return 0;
}

void g()
{
float n = 42;
f(100); /* if parameter 'f' of function 'f()' were
not declared 'const', there would be no
compiler error, but the run-time behavior
would be undefined (if you're lucky, some
visible problem e.g. 'seg fault'), since
'100' is a constant which must not be modified. */

f(n); /* Suppose your code required that 'n' should be
able to be modified in this scope, but not others.
If function 'f()'s parameter 'f' were not 'const'
it could change 'n'. With 'const', you'd get
a complaint from the compiler. */

}

So, if and when to use 'const' depends upon your needs.

-Mike

Hmm.... maybe my compiler is retarded,


No, my example was. :-)

I meant to write

f(&n);

-Mike
Mar 20 '06 #9

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

Similar topics

8
by: Sergey Tolstov | last post by:
Hello, I am working with Visual C++ 6.0 compiler. In the following declaration: int const A = 10, B = 10; both A and B are const. However, in declaration
20
by: Corno | last post by:
Hi all, There's probably a good reason why a const object can call non const functions of the objects where it's member pointers point to. I just don't see it. For me, that makes the the const...
6
by: Virendra Verma | last post by:
This sounds weird, but I am looking for separate behaviors for destruction of a const and non-const object. I am trying to develop a smart/auto pointer class for writing objects to disk...
7
by: johny smith | last post by:
Can someone please explain to me the difference between these two: function1( const int a) function2( int const a) Both seemed to compile, but what is the difference between the two above....
3
by: Steven T. Hatton | last post by:
Sorry about the big code dump. I tried to get it down to the minimum required to demonstrate the problem. Although this is all done with GNU, I believe the problem I'm having may be more general. ...
15
by: Dave | last post by:
Hello NG, It is well known that memory-allocating definitions should not be put in a header file. I believe, however, that this does not apply to const definitions. For example: #ifndef...
4
by: chrisstankevitz | last post by:
This code does not compile on gcc 3.4.4. Should it? Thanks for your help, Chris //================ #include <set> int main()
10
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
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,...
4
by: grizggg | last post by:
I have searched and not found an answer to this question. I ran upon the following statement in a *.cpp file in a member function: static const char * const pacz_HTMLContentTypeHeader =...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.