分号和逗号在C [英] Semicolon and Comma in c

查看:317
本文介绍了分号和逗号在C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这些程序工作,为什么我没有得到一个分号丢失的错误?带着这个问题我要问,当我可以跳过分号。据我所知分号句子终止。它是正确的写这些类型在这里我们使用逗号而不是分号语句。在程序1有一个否定,然后打印,然后的getchar()在一行中没有分号,并用逗号。同样在计划2否定,分配,printf和getchar函数()全部被使用。我们有多少行可以编写使用逗号,而不是使用分号。

程序1:

 的#include<&stdio.h中GT;
诠释的main()
{
   INT I =和0xAA;
   〜我的printf(%X \\ n,I),getchar函数();
   返回0;
}

方案二:

 的#include<&stdio.h中GT;
诠释的main()
{
   INT I =和0xAA;
   I =〜我的printf(%X \\ n,I),getchar函数();
   返回0;
}


解决方案

这是因为逗号是C.运营商根据C编程语言的第二版:


  

一对用逗号分​​隔的前pressions是从左向右计算的,结果的类型和值就是右操作数的类型和值。


要知道,虽然,那它也说:


  

这是分隔函数参数的逗号,在报关单等变量,是的的逗号运营商,并且不保证从左到右的评价。


忘记这个的一个常见的​​例子说明<一href=\"http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc\">here.

所以,这两个方案是正确的(虽然只在第二个我打印的反转值)。

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;
}

解决方案

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).

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

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