3 ms·
I find it the opposite, when I read code that doesn't use const at all. In that case you want to make sure that code doesn't change either the value the pointe
by slug 16y ago
I find it the opposite, when I read code that doesn't use const at all. In that case you want to make sure that
code doesn't change either the value the pointer is pointing to and where the pointer is pointing to :)
<pre>
#include <stdio.h>
void function ( int const * const value )
{
printf ("%d\n", * value);
/ * more code * /
( * value)++;
/ * more code * /
++value;
}
int main(int argc, char * * argv)
{
int value = 1;
int * pvalue = &value;
function(pvalue);
return 0;
}
$ gcc t1.c
t1.c: In function ‘function’:
t1.c:5: error: increment of read-only location ‘* value’
t1.c:7: error: increment of read-only location ‘value’
</pre>
quick googling:
http://www.cprogramming.com/tutorial/const_correctness.html http://www.cprogramming.com/tutorial/const_correctness.html
EDIT: how can we properly paste code in here? The * mess things up.
- parenthesis 16y agohttp://news.ycombinator.com/formatdoc http://news.ycombinator.com/formatdoc
- pietrofmaggi 16y agoUsually you take a look at the FAQ and read the http://news.ycombinator.com/formatdoc http://news.ycombinator.com/formatdoc page. #include <stdio.h> void function(int const * const value) { printf ("%d\n", *value); /* more code */ (*value)++; /* more code */ ++value; } int main(int argc, char **argv) { int value = 1; int *pvalue = &value; function(pvalue); return 0; } $gcc t1.c t1.c: In function ‘function’: t1.c:9: error: increment of read-only location t1.c:13: error: increment of read-only location BTW: I agree, const is really useful EDIT: I've recompiled on OSX to correct the error message with the correct lines.
- duncanj 16y agoI think you misunderstand. When I see, in a function like yours void function(int const * const value) it worries me because it shows me that the writer doesn't know the meaning of const. There is no added value of this declaration over void function(int const *value) or the more commonly seen void function(const int *value) The only thing that has changed in your code is that the implementor of the function can't modify his own private copy of the pointer.