In the function printf why "const char *" is used?
In the function printf why "const char *" is used?
Do you mean why is the format string of that type? Because that's the type of a string literal, especially one that printf should not be changing.
I dont get your question correctly but what we write inside printf is a string literal and is non-writable. Eg.
I think this is what you're asking.Code:printf("Hello World"); // string literal and can't be modified
HOPE YOU UNDERSTAND.......
By associating with wise people you will become wise yourself
It's fine to celebrate success but it is more important to heed the lessons of failure
We've got to put a lot of money into changing behavior
PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
Kerninghan Ritchie, chapter 5
Perhaps the most common occurrence of string constants is as arguments to functions, as in
When a character string like this appears in a program, access to it is through a characterCode:printf("hello,world\n");
pointer; printf receives a pointer to the beginning of the character array. That is, a string
constant is accessed by a pointer to its first element.
HOPE YOU UNDERSTAND.......
By associating with wise people you will become wise yourself
It's fine to celebrate success but it is more important to heed the lessons of failure
We've got to put a lot of money into changing behavior
PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
Well thanks a lot for all your help.
But what I need to ask is why 'const' is used in printf prototype. If the reason is it should not be changing then why in numerical functions 'const' is not used such as in sqrt and others. Hope you all get me now...
I think Tabstop answered your question. The format string is a string literal, that should not be modified by printf. If it was necessary that the parameter variables should not change in pow or sqrt, they would be declared const as well. However, with functions like pow and sqrt, you are really only passing in a copy of the variable, and so even if they do get modified, it does not change the variable outside of the function. With the string literal passed to printf, what you are getting is a pointer to the string, which could then be used to modify the original (Though I think any tampering with the string literal would produce a segfault these days), which is undesirable.
Last edited by kermit; 09-21-2009 at 08:58 AM.