c - 指针初始化无法识别定义的类型

标签 c pointers c-preprocessor typedef

尝试定义用户类型时,我偶然发现了一个我不太明白的错误:以下代码工作正常

const int a[5] = { 1, 2, 3, 4, 5 };

typedef const int costant;

costant b = 5;
costant *c = a;

void func( const int item )
{
    printf("Item: %i\n", item );
}

int main( void )
{
    func( a[0] );
    func( b );
    func( *c );
}

尽管如此,初始化指针

costant *c = a[0];

未能说明Initializer element is not costant 。尝试访问位置a[0]更改其内容被拒绝,并出现错误 assignment of read-only location .

为什么被认为是数组地址a作为 const 但不是其元素 a[0] ,即使它是“只读”?

替换 typedef#define costant const int不会改变行为。

最佳答案

#define 的语法为 #define NEW_SYMBOL [o​​ld_symbol] 不同,typedef 的语法为:

typedef existing_type new_type;

所以:

typedef const int constant;

C 有效,而

typedef constant const int;

不是。

关于c - 指针初始化无法识别定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467792/

相关文章:

使用预处理器检查表达式是否为左值

c++ - 我可以从静态 const char* 数组定义以下宏 "unstringifying"吗?

c 链表 - 是否可以创建一个独立于负载的迭代器函数?

c++ - 为什么 AutoSuggestion List 在 MFC 中输入时不关闭?

c - C - 乘法或除法中哪个优先级更高?

c - 分配结构指针数组

c - 下面的代码生成 32x32 hadamard 矩阵。但是我如何递归地编写它呢?

c - 如何解释输出?

c++ - 在数组中使用 const char * 读取顺序文件

你能用 C#define 注释吗?