[prog] Another elementary 'C' question
John Stoneham
lyric.programming at lyrically.net
Tue Dec 14 09:06:25 EST 2004
> int fprintf(FILE *stream, const char *format, ...)
>
> Now, I imagine that the 'const' there means that fprintf won't change
> the contents of the string *format.
True. In fact the compiler won't let it. This would be a syntax error.
> But presumably it doesn't change the value pointed to by 'stream'
> either, otherwise we'd get in a right old mess with subsequent actions
> on the relevant file. But FILE isn't shown as 'const'.
I think you're missing the point of fprintf here, which is indeed to change
the fstream you're pointing to... otherwise nothing could be printed!
What might be confusing you is that it changes the internal state of stream,
but it can't rewrite the value of that pointer within your own code. i.e.
FILE *myStream = /* something here */;
fprintf(myStream,"foo bar");
myStream will always point to the same thing you set it to, since fprintf
can't rewrite the value of that variable in your program unless you give it a
pointer to that variable (which would be a FILE **, not a FILE *). The value
of the pointer is passed by copy, just as the object would have been had the
function not taken a pointer. Make sense?
Const gets more fun when you have functions with signatures like this:
const int *const myFunction(const char *const charPtr) const;
... which I can explain if you are interested. :) (You can only get that last
const in C++, too.)
- John
More information about the Programming
mailing list