Reputation: 438
Why does the following code compiles?
void foo(const LPSTR str) {
str[0] = '\0';
}
while
void foo(LPCSTR str) {
str[0] = '\0';
}
and
void foo(const char* str) {
str[0] = '\0';
}
does not.
It's actually LPTSTR
in my code so const
version is LPCTSTR
...
So can I increase code readability by having something like const LPTSTR
, or it must be either LPCTSTR
or const TCHAR*
?
Upvotes: 3
Views: 3118
Reputation: 238351
If you take a look at the documentation you'll find that LPSTR
is an alias of CHAR *
, while CHAR
is in turn an alias of char
. Therefore LPSTR
is an alias of char*
.
Why const LPSTR is different than const char *?
const
in const char *
applies to the char
. In other words, it is a non-const pointer to const object.
const
in const LPSTR
applies to LPSTR
, which as we have discovered is char*
. Because LPSTR
is a pointer, this makes the pointer const. It does not have an effect on whether the pointer points to a const or non-const object. So, the type is char * const
.
As for why does str[0] = '\0';
not compile when str
is const char*
, the reason is that you may not modify const objects. It compiles with char * const
, because you may modify non-const objects.
PS. The fact that this question exists, demonstrates how hiding the data-pointer types behind aliases is confusing.
Upvotes: 2
Reputation: 385144
Because a LPCSTR
is not the same as a (hypothetical) CLPSTR
.
Upvotes: -3
Reputation: 1593
const LPSTR
is resolved as char* const
: Only the pointer is constant you can modify its content. Look at its definition here. So your first example compileLPCSTR
is resolved as const char*
so you can't modify its content. You can see its definition here. So your second example does not compileconst char*
you can not modify its content, so your last example does not compileUpvotes: 0
Reputation: 171127
A typedef "seals" the type from outside modification. LPSTR
is a char *
, period. Adding const
to that (as const LPSTR
) adds the const
to the outside: you get a char * const
.
What you want is to "inject" the const
(apply it the pointee, not to the pointer), and that is not possible through a simple declaration syntax with a typedef. So it must be LPCSTR
, the typedef created for exactly this purpose.
Upvotes: 8