typedef'ng a pointer and const

我与影子孤独终老i 提交于 2020-07-08 05:38:47

问题


I was looking at an example which showed that why typedef'ng a pointer is a bad practice. 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. 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. I am sure I am missing something very basic.


回答1:


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 TYPE x is saying that the pointer value should be constant. This is roughly equivalent to 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.

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 const int * CONST_TYPE;

However, at this point the typedef seems to be causing more trouble than it solves... Probably not the best idea.



来源:https://stackoverflow.com/questions/34857341/typedefng-a-pointer-and-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!