How can I declare constant strings and what use are they in programming? I don't know If I'm doing this right but would this be the correct way of doing it?:
const char my_string="Hello";
How can I declare constant strings and what use are they in programming? I don't know If I'm doing this right but would this be the correct way of doing it?:
const char my_string="Hello";
const char my_string="Hello";
This is not valid C. A string literal like "hello"
is of type char[n]
, not const char
. The correct declaration is
const char my_string[] = "Hello";
Also, its a good idea to name your constants in ALLCAPS.
here's the answer:
Method 1
const char my_string[] = "Hello";
Method 2
const char *my_string="Hello";
as you ask why it is used in C Programming the answer is when we want the value to remain the same and to protect the value from being overwritten we declare the variable as constant.
In the C programming language, the meaning of const
is much less powerful than it is in other, more-recent, languages. In fact, it could well be said that the meaning is not the same at all.
To quote http://www.geeksforgeeks.org/const-qualifier-in-c/ ... (emphasis and omissions mine):
The qualifier
const
can be applied to the declaration of any variable to specify that its value will not be changed [...] The outcome is implementation-defined(!) if an attempt is made to change a const.
The key thing to notice here is that, in C (which, in its defense, dates from the 1970's), the keyword const
is a qualifier. It is not a "compile-time constant!"
The C language used #define
declarations as its closest approximation to the behavior that other languages use when presented with the keyword, const
.
Consider the following web-page, "The C++ 'const' declaration, Why & How," where author Andrew Hardwick frankly discusses the treatment of this keyword in both the C and the C++ languages: http://duramecho.com/ComputerInformation/WhyHowCppConst.html
Contrast both of these languages to other languages' treatment of this word, which they consider to be a declaration (not a qualifier), and which they universally treat in an entirely different way.