This is only useful if buf is involved in some preprocessor macrology which perpetrates a hidden mutation of buf. BIG_MACRO(x, y, z, buf); // error!
the programmer is informed that, to his or her surprise, BIG_MACRO mutates buf and can take appropriate corrective action.It's also useful in C++, since innocent-looking function calls can steal mutable references: cplusplusfun(x, y, z, buf); // error: arg 4 is non-const ref
No such thing in C, though; function calls are pure pass-by-value.Changing pointers returned by malloc is sometimes done: if ((newptr = realloc(buf, newsize)) != 0)
buf = newptr;
else
...
In my experience, C code doesn't use const for anywhere near all of the local variables which could be so qualified.If you enact a coding convention that all unchanged variables must be const, the programmers will just get used to a habit of removing the const whenever they find it convenient to introduce a mutation to a variable. "Oh, crap, error: x wasn't assigned anywhere before so it was const according to our coding convention. Must remove const, recompile; there we go!" If you want to actually enforce such a convention of adding const, you need help from the compiler: a diagnostic like "foo.c: 123: variable x not mutated; suggest const qualifier". I've never seen such a diagnostic; do you know of any compiler which has this? I think that the average C module would spew reams of these diagnostics. |