如何用逗号 (,) 分隔两个 C 语句?
How am I able to separate two C statements by a comma (,)?
我正在编辑我几天前编写的程序的源代码,并观察到一件有趣的事情。
我有以下两个陈述:
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 语句。但是,您可以用逗号分隔两个 C expressions,因为 , 是一个运算符(按顺序计算其两个操作数,先左后右)然后是右边,最后 returns 右边那个)。
此外,a = b
是一个表达式。但是,其中一种可能的 C 语句类型是表达式,因此您可以使用任何表达式作为语句,包括 a + b;
、a = b;
和 a = b, a + b;
我正在编辑我几天前编写的程序的源代码,并观察到一件有趣的事情。
我有以下两个陈述:
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 语句。但是,您可以用逗号分隔两个 C expressions,因为 , 是一个运算符(按顺序计算其两个操作数,先左后右)然后是右边,最后 returns 右边那个)。
此外,a = b
是一个表达式。但是,其中一种可能的 C 语句类型是表达式,因此您可以使用任何表达式作为语句,包括 a + b;
、a = b;
和 a = b, a + b;