I'm not sure. What's the difference between:
...and:Code:int somemethod(char *a1, char *a2)
?Code:int somemethod(const char *a1, const char *a2)
Best wishes, Desmond5
Printable View
I'm not sure. What's the difference between:
...and:Code:int somemethod(char *a1, char *a2)
?Code:int somemethod(const char *a1, const char *a2)
Best wishes, Desmond5
the second function notifies the caller that it will not modify the contents of the buffer pointer by their parameters. As a result - programmer will know that it is safe to pass string literal like "Hello" into this function.
The first function may modify the buffer, so generally speaking - to pass string literal into it - it should be first copied into modifiable buffer.
Const tells the compiler that you cannot and will not change the contents of the variables to which the const applies.
Note that you can have a pointer to a const type and a const pointer itself. This example uses a pointer to a const type, which is more common since it will guard the contents pointed to by the pointer from being changed.
Const is partly to stop silly mistakes and partly to also enable some optimizations for the compiler.
I don't think any modern compilers would actually optimize a program based on whether const was present or not . . . it's kind of like the register keyword. I'm not sure on this, but that's what I think.Quote:
Const is partly to stop silly mistakes and partly to also enable some optimizations for the compiler.
As far as I know, const is indeed merely to help the compiler point out where you're doing something you told it you shouldn't be.
I have read of at 1 case a while ago where VS (2005 I think) does generate slightly more optimal code when const is used. It was not for a function parameter though.
Const forbids the change of the variable. While you could have some math upon initiating it, it cannot be changed after this. I have a few of these in my functions, usually as local variables and string parameters. Other globals have it as well are basically quick conversions. Here's a few examples:
Code:const double pi = 3.1415926535897932; // you should recognize this one
double degrees = 57.295779513082321// converts radians to degrees when multiplying
int ProcessText(const char string[100], other parameters)
{
short Variable; // uninitialized
const long UnchangingVariable = 8; // a local that can't change
const float NonchangingVariable = 32.8*degrees; // a local with some math used that can't change after this
}
It would be the same. If something is read-only, that means that it cannot be changed and "const forbids the change of the variable" means that the value of the variable cannot be changed. They mean the same thing, though your "read-only" approach is much clearer.
read-only var could be changed in other part of the code, where the access is done without const qualifier