Const qualifier ignored [duplicate]
문제
I have a struct type_s. Then I typedef a pointer to a struct type_s as type.
If I have a const struct type_s*
then the compiler will correctly complain if an assignment is made to the struct member, as seen in function Test1(). But if I make a const type, which is a typedef for the same struct pointer the compiler will not complain and compile, function Test2().
typedef struct type_s* type ;
struct type_s
{
int a ;
} ;
void Test1( const struct type_s* t )
{
t->a = 123 ; //complains, ok
}
void Test2( const type t )
{
t->a = 123 ; //doesn't, it should in my oppinion
}
To me they are logically both the same thing. What am I missing?
Is the only solution to create another typedef for a constant pointer to that struct like this:
typedef const struct type_s* ctype ;
which will work correctly as in Test1().
해결책
What you're missing is that a const pointer is not the same thing as a pointer to a const object. You have one of each. A const pointer is a pointer whose stored address is not modifiable; a pointer to const is one which cannot be used to modify its referent.
다른 팁
They are not the same thing. const
has different semantics when applied to the definition or declaration of a pointer variable and a non-pointer variable.
const struct type_s *t
The above statement defines t
to be a pointer to an object of type const struct type_s
. Here, const
qualifies the type struct type_s
of the object t
points to, not the pointer t
.
typedef struct type_s *type ;
The above statement defines an alias named type
for the type struct type_s *
.
const type t;
// equivalent to
type const t;
// equivalent to
struct type_s *const t;
The above statement defines t
to be a constant object of type type
. Here const
qualifies the object. You cannot replace the typedef
with its original type and reinterpret it as if it were a macro. The pointer information is embedded in the typedef
and it will be treated as a non-pointer type.