以下代码运行良好,但我找不到用()
初始化数组的基础。有人能解释一下吗?
#include <stdio.h>
int main(void){
int a[3][2] = {(0, 1), (2, 3), (4, 5)};
printf("%#xn", a[0]);
printf("%#xn", a[1]);
return 0;
}
(0, 1)
表达式使用逗号运算符。并且可以将其优化为1。
请阅读本C参考资料和一些C标准,如n1570或更新版本。
你可能想编码:
int a[3][2] = {{0, 1}, {2, 3}, {4, 5}};
和
printf("%#xn", a[0]);
是错误的,您正在打印指针。所以使用%p
而不是%#x
如果使用调用为gcc -Wall -Wextra -g
的GCC进行编译,则会收到警告:
% gcc -Wall -Wextra -g /tmp/articfox.c -o /tmp/articfox
/tmp/articfox.c: In function ‘main’:
/tmp/articfox.c:4:22: warning: left-hand operand of comma expression has no effect [-Wunused-value]
4 | int a[3][2] = {(0, 1), (2, 3), (4, 5)};
| ^
/tmp/articfox.c:4:30: warning: left-hand operand of comma expression has no effect [-Wunused-value]
4 | int a[3][2] = {(0, 1), (2, 3), (4, 5)};
| ^
/tmp/articfox.c:4:38: warning: left-hand operand of comma expression has no effect [-Wunused-value]
4 | int a[3][2] = {(0, 1), (2, 3), (4, 5)};
| ^
/tmp/articfox.c:4:19: warning: missing braces around initializer [-Wmissing-braces]
4 | int a[3][2] = {(0, 1), (2, 3), (4, 5)};
| ^
| { } { }
/tmp/articfox.c:5:15: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
5 | printf("%#xn", a[0]);
| ~~^ ~~~~
| | |
| | int *
| unsigned int
| %#ls
/tmp/articfox.c:6:15: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
6 | printf("%#xn", a[1]);
| ~~^ ~~~~
| | |
| | int *
| unsigned int
| %#ls
C.中没有括号运算符:(
如果去掉括号,那么数组的初始化将看起来像
int a[3][2] = { 0, 1, 2, 3, 4, 5};
这就是初始值设定项列表恰好包含6个显式初始值设定值。
括号允许您使用更复杂的表达式作为初始值设定项。因此,在本声明中
int a[3][2] = {(0, 1), (2, 3), (4, 5)};
只有3个显式初始值设定项。数组中除前三个元素外的所有其他元素都将被零初始化。
括号中的表达式是带有逗号运算符的表达式。每个表达式的值都是最右边操作数的值。因此,上述声明相当于
int a[3][2] = { 1, 3, 5 };
考虑以下演示程序。
#include <stdio.h>
int main(void)
{
int i = 10;
int x = ( i++, ++i );
printf( "x = %dn", x );
return 0;
}
其输出为
x = 12
如果要删除此声明中的括号
int x = i++, ++i;
那么编译器会认为,在您想要声明的标识符列表中,您忘记了逗号后面的第二个标识符,类似于
int x = i++, y = ++i;