C 多行单行声明 [英] C multiple single line declarations

查看:29
本文介绍了C 多行单行声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在一行中声明多个变量时会发生什么?例如

What happens when I declare say multiple variables on a single line? e.g.

int x, y, z;

都是整数.问题是以下语句中的 y 和 z 是什么?

All are ints. The question is what are y and z in the following statement?

int* x, y, z;

都是int指针吗?

推荐答案

只有 x 是一个指向 int 的指针;yz 是常规整数.

Only x is a pointer to int; y and z are regular ints.

这是 C 声明语法的一个方面,它让一些人感到困惑.C 使用声明符的概念,它引入了被声明的事物的名称​​以及类型说明符未提供的附加类型信息.在声明中

This is one aspect of C declaration syntax that trips some people up. C uses the concept of a declarator, which introduces the name of the thing being declared along with additional type information not provided by the type specifier. In the declaration

int* x, y, z;

声明符是 *xyz(这是 C 语法的一个意外,您可以将 int* xint *x,这个问题是我推荐使用第二种风格的几个原因之一).xyz 的完整性由类型说明符 int 指定,而指针-ness of x 由声明符 *x 指定(IOW,表达式 *x 的类型为 int).

the declarators are *x, y, and z (it's an accident of C syntax that you can write either int* x or int *x, and this question is one of several reasons why I recommend using the second style). The int-ness of x, y, and z is specified by the type specifier int, while the pointer-ness of x is specified by the declarator *x (IOW, the expression *x has type int).

如果您希望所有三个对象都成为指针,您有两种选择.您可以将它们显式声明为指针:

If you want all three objects to be pointers, you have two choices. You can either declare them as pointers explicitly:

int *x, *y, *z;

或者你可以为 int 指针创建一个 typedef:

or you can create a typedef for an int pointer:

typedef int *iptr;
iptr x, y, z;

请记住,在声明指针时,* 是变量名称的一部分,而不是类型.

Just remember that when declaring a pointer, the * is part of the variable name, not the type.

这篇关于C 多行单行声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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