typedef'ng指针和const [英] typedef'ng a pointer and const

查看:62
本文介绍了typedef'ng指针和const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个示例,该示例表明为什么对指针进行类型定义是一种不好的做法。我对示例不了解的部分是为什么编译器无法解决问题。我将示例详细说明为以下代码:

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;
}

因此,我能够更改的值一个。即使该示例说明您必须执行 typedef const int * TYPE 来解决该问题,但我不明白为什么编译器无法捕获该错误当我在函数参数本身中将 TYPE设置为const 时。我确定我缺少一些非常基本的东西。

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.

推荐答案

这里的问题是关于 const 应用于:是应用于指针值本身,还是指向该值?

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 表示指针值应该是恒定的。这大致相当于 int * const x 。请注意,以下代码确实导致错误:

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)

您期望的是 const int * x ,这使x指向的值成为常数。

What you were expecting is const int * x, which makes the value pointed to by x a constant.

由于typedef隐藏了事实 TYPE 是指针类型,无法指定 TYPE 所指向的东西应该是 const ,除了声明另一个typedef:

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;

但是,在这一点上,typedef似乎造成的麻烦超过了解决的范围……可能不是最好的主意。

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

这篇关于typedef'ng指针和const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆