c - typedef 和变量名

标签 c variables scope declaration typedef

忽略我为什么要这样做,只是想了解这里发生了什么: 此代码编译:

#include <stdio.h>
typedef char byte;

int main (void) 
{
    byte var_byte;
    int byte = 10;

    printf("\n Test program: %d\n", byte);
}  

但是,如果我改变声明变量的顺序,它就不会编译。

这不编译:

#include <stdio.h>
typedef char byte;

int main (void)
{
    int byte = 10;
    byte var_byte;

    printf("\n Test program: %d\n", byte);
}

编译器错误:

b.c:7:8: error: expected ‘;’ before ‘var_byte’
   byte var_byte;
        ^~~~~~~~

有人可以解释为什么顺序很重要吗?

最佳答案

在这个程序中

#include <stdio.h>
typedef char byte;

int main (void)
{
    int byte = 10;
    byte var_byte;

    printf("\n Test program: %d\n", byte);
}

变量 byte 的名称隐藏了 typedef 的名称。

来自 C 标准(6.2.1 标识符的范围)

  1. ... If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

注意标识符的名称和typedef名称属于同一个 namespace 。

typedef 名称在全局作用域(文件作用域)中声明,而变量名称在内部 block 作用域中声明,变量名称隐藏在全局作用域中声明的名称。

考虑这个程序。

#include <stdio.h>
typedef char byte;

void f( void );

int main (void)
{
    int byte = 10;

    printf("\n Test program: %d\n", byte);

    f();
}

void f( void )
{
    byte c = 'A';
    printf( "%c\n", c );
}

在函数 main 的 block 范围内(相对于文件范围的内部范围),typedef 的名称被同名变量的声明隐藏。

但是在函数 f 的 block 范围内,typedef 中声明的名称是可见的,因为函数 block 范围内的其他声明都没有隐藏 typedef 中声明的名称。

这是一个更有趣的程序,它处理声明点(这是一个 C++ 术语)

#include <stdio.h>

size_t byte = 255;

int main(void) 
{
    typedef int byte[byte];

    {
        byte byte;

        printf( "sizeof( byte ) = %zu\n", sizeof( byte ) );
    }

    return 0;
}

它的输出可能看起来像

sizeof( byte ) = 1020

在文件作用域中声明了一个名为 byte

的变量
size_t byte = 255;

在函数 main 的外部 block 作用域中引入了 typedef name byte

typedef int byte[byte];

它在声明符声明后隐藏先前声明的名称byte。那就是在这个 typedef 中

    typedef int byte[byte];

方括号中的名称byte对应全局名称byte

然后在内部 block 作用域中声明了一个具有相同名称 byte 的数组,它隐藏了 typedef 名称。

byte byte;

注意表达式中的那个

sizeof( byte )

这里使用的是数组的名称而不是 typedef 名称。

关于c - typedef 和变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383503/

相关文章:

java - 继承方法调用 - Java

java - 为什么我的 Java 方法不能更改传递的变量?

javascript变量作用域

java - Spring批处理: org. springframework.beans.factory.BeanCreationException:使用JobScope时创建名称为 'scopedTarget.writer'的bean时出错

java - 将 DLL 与 JNA 一起使用时 C 中的堆损坏

c - 尽管RAW套接字和HDRINCL,IP源地址仍然由系统填充

variables - Tcl $argc 和 $argv 变量

函数超出范围后,C++ 对象数据被清除

c - 字符串比较在 C 中不起作用

c - 简单的 2000 次抛硬币模拟器显示 2000 多个结果