const限定符被忽略

时间:2014-04-13 14:33:54

标签: c const typedef c99

我有一个struct type_s。然后我输入一个指向结构type_s的指针作为类型。

如果我有const struct type_s*,那么如果对结构成员进行了赋值,则编译器将正确地抱怨,如函数Test1()中所示。但是如果我创建一个const类型,它是同一结构指针的typedef,编译器就不会抱怨和编译,函数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
}

对我而言,他们在逻辑上都是一回事。我错过了什么?

是唯一的解决方案,为这个结构的常量指针创建另一个typedef,如下所示:

typedef const struct type_s* ctype ;

将在Test1()中正常工作。

2 个答案:

答案 0 :(得分:2)

你缺少的是const指针与指向const对象的指针不同。你有一个。 const指针是一个指针,其存储的地址不可修改;指向const的指针是一个不能用于修改其指示对象的指针。

答案 1 :(得分:1)

他们不是一回事。 const在应用于指针变量和非指针变量的定义或声明时具有不同的语义。

const struct type_s *t 

上述语句将t定义为指向const struct type_s类型对象的指针。在这里,const限定对象struct type_s的类型t,而不是指针t

typedef struct type_s *type ;

上述语句为类型type定义名为struct type_s *的别名。

const type t;
// equivalent to
type const t;
// equivalent to
struct type_s *const t;

上述语句将t定义为type类型的常量对象。这里const限定了对象。您不能将typedef替换为其原始类型,并将其重新解释为它是一个宏。指针信息嵌入在typedef中,它将被视为非指针类型。

相关问题