473,624 Members | 2,122 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2656

"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.goo glegroups.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
2583
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
2487
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 keyword a lot less usable. Can anybody tell me what that good reason is? TIA,
6
2415
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 implicitly. The destructor of this class saves the object to the disk if it is dirty. The problem comes in the following scenario when a function returns an uncommitted pointer class because same copies will be committed as two separate objects on disk....
7
3789
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. And why would one choose one over the other. moreover, I thought there was a difference between the two below where one would not let the value change whereas the other one would not let the
3
2228
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. Someone on the SuSE programming mailing list suggested my problem is that I'm trying to execute a function (I assume he meant the constructor) at compile time. The same source code compile if I don't try to split it up into separate libraries. ...
15
4172
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 MY_HEADER #define MY_HEADER const int FOO = 42;
4
2744
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
2774
by: d3x0xr | last post by:
---- Section 1 ---- ------ x.c int main( void ) { char **a; char const *const *b; b = a; // line(9)
0
1867
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 begin at the low level weeding out references of 'passing const char * to char * ( such as...
4
6682
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 = "Content-Type: text/html\r\n"; Why is the second const needed and what does it do? Thanks
0
8621
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8335
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
7159
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6110
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5563
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4079
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2606
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
1785
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.