Semicolon and Comma in c [closed]

2019-02-21 09:38发布

Why do these programs work, and why do I not get a "semicolon missing" error? With this question i want to ask that when i can skip semicolons. As far as i know semicolon is sentence terminator. Is it correct to write these type of statements where we use comma instead of semicolon. In program1 there's a negation then printing and then getchar() in one line without semicolon and using comma. similarly in program 2 negation,assignment,printf and getchar() all are used. How much line we can write using comma and not using semicolon.

program1:

#include <stdio.h>
int main()
{
   int i = 0xAA;
   ~i, printf("%X\n", i),getchar();
   return 0;
}

program 2:

#include <stdio.h>
int main()
{
   int i = 0xAA;
   i=~i, printf("%X\n", i),getchar();
   return 0;
}

2条回答
▲ chillily
2楼-- · 2019-02-21 09:53

Why semicolon missing error is not coming in c

Because it is not missing.

查看更多
叛逆
3楼-- · 2019-02-21 09:55

It is because the comma is an operator in C. According to the second edition of The C Programming language:

A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand.

Be aware though, that it also says:

The commas that separate function arguments, variables in declarations etc., are not comma operators, and do not guarantee left to right evaluation.

A common example of forgetting this is explained here.

So both programs are correct (though only in the second one the inverted value of i is printed).

查看更多
登录 后发表回答