简体   繁体   English

typedef'ng指针和const

[英]typedef'ng a pointer and const

I was looking at an example which showed that why typedef'ng a pointer is a bad practice. 我正在看一个例子,它表明为什么typedef'ng指针是一种不好的做法。 The part I didn't understand about the example is that why the compiler wasn't able to catch the problem. 我对该示例不了解的部分是为什么编译器无法捕获问题。 I elaborated the example into the following code: 我在下面的代码中详细说明了这个例子:

#include <stdio.h>

typedef int *TYPE; 

void set_type(TYPE t) {
    *t = 12;
}

void foo(const TYPE mytype) {   
    set_type(mytype);  // Error expected, but in fact compiles 
}

int main() {   
    TYPE a;
    int b = 10;
    a = &b;
    printf("A is %d\n",*a);
    foo(a);
    printf("A is %d\n",*a);

    return 0;
}

So, I was able to change the value of a . 所以,我能够改变的值a Even though, the example explained that you would have to do, typedef const int *TYPE , to solve the problem, I dont understand why the compiler was not able to catch the error when I am setting TYPE to be const in the function argument itself. 即便如此,该示例解释说,你将不得不这样做, typedef const int *TYPE ,要解决这个问题,我不明白为什么编译器没能赶上,当我设置错误TYPE to be const在函数参数本身。 I am sure I am missing something very basic. 我确信我遗漏了一些非常基本的东西。

The issue here is confusion about what const is being applied to: is it applied to the pointer value itself, or the value being pointed to? 这里的问题是关于const应用于什么的混淆:它是应用于指针值本身,还是应用于指向的值?

const TYPE x is saying that the pointer value should be constant. const TYPE x表示指针值应该是常量。 This is roughly equivalent to int * const x . 这大致相当于int * const x Note that the following code does result in an error: 请注意,以下代码确实会导致错误:

int b = 10;
const TYPE p = NULL;
p = &b; // error here (assign to const)

What you were expecting is const int * x , which makes the value pointed to by x a constant. 您期望的是const int * x ,它使x指向的值为常量。

Since the typedef hides the fact that TYPE is a pointer type, there's no way to specify that the thing pointed to by TYPE should be const , aside from declaring another typedef: 由于typedef隐藏了TYPE是指针类型的事实,除了声明另一个typedef之外,没有办法指定TYPE指向的东西应该是const

typedef const int * CONST_TYPE;

However, at this point the typedef seems to be causing more trouble than it solves... Probably not the best idea. 然而,在这一点上,typedef似乎造成了比它解决的更多麻烦......可能不是最好的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM