【发布时间】:2023-03-08 11:29:01
【问题描述】:
我正在编辑几天前编写的程序的源代码,并观察到一件有趣的事情。
我有以下两个陈述:
newNode->data = 5
和
newNode->next = NUll
并且有一个逗号 (,) 而不是分号 (;) 分隔上述两个语句。我很惊讶,因为我一直认为这会导致错误。
下面,我写了一个简短的 C 程序来说明我的意思。
#include<stdio.h>
#include<stdlib.h>
/*node structure definition*/
struct node
{
int data;
struct node *next;
};
/*----------main()------------*/
int main(int argc, char *argv[])
{
struct node *newNode = NULL;
newNode = malloc(sizeof(struct node));
/*Below is the interesting statement*/
/*LABEL: QUESTION HERE*/
newNode->data = 5,
newNode->next = NULL;
printf("data: %d\n",newNode->data);
while(newNode->next != NULL)
{
printf("Not Null\n");
}
return 0;
}
请看下面的上述程序的编译和示例运行。
Lunix $ gcc -Wall testComma.c -o testComma
Lunix $ ./testComma
data: 5
Lunix $
如您所见,程序编译并运行没有问题。
在这里使用逗号 (,) 代替分号 (;) 应该不会导致错误?为什么 ?
我以为我知道 C 语句是什么,但看起来我不知道!有人能解释一下这种情况下没有错误的原因吗?
【问题讨论】:
-
在 C 中看到逗号运算符的最常见位置是在具有多个初始化的
for循环中。许多语言都以类似的方式支持逗号运算符,包括 C++、Java、C# 和 Perl。