C 语言 中关于 顺序点(Sequence points) 的问题

本文详细介绍了C语言中的顺序点(sequence point)概念及其在标准中的定义。通过具体示例展示了违反顺序点规则可能导致的未定义行为,强调了使用-Wsequence-point选项检查潜在问题的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     关于顺序点(sequence point),在C标准中有解释,不过很晦涩。

 

     The sequence points laid down in the Standard are the following:

  • The point of calling a function, after evaluating its arguments.
  • The end of the first operand of the && operator.
  • The end of the first operand of the || operator.
  • The end of the first operand of the ?: conditional operator.
  • The end of the each operand of the comma operator.
  • Completing the evaluation of a full expression. They are the following:
    • Evaluating the initializer of an auto object.
    • The expression in an ‘ordinary’ statement—an expression followed by semicolon.
    • The controlling expressions in do , while , if , switch or for statements.
    • The other two expressions in a for statement.
    • The expression in a return statement.

 

我们在平时编码中尽量避免写出与实现相关、受实现影响的代码便是了。而-Wsequence-point选项恰恰可以帮我们这个忙,它可以帮我们查出这样的代码来,并给出其警告。
e.g.

gcc -Wsequence-point test_sequence_point.c
test_sequence_point.c: In function `main':
test_sequence_point.c:10: warning: operation on `i' may be undefined
在两个平台上给出的编译警告都是一致的,但是输出结果却大相径庭。


Solaris输出:
the i is 11
Windows输出:
the i is 12
类似的像这种与顺序点相关的代码例子有:

 

 


这样子的代码往往不能按照你所想像的结果输出,所以这样子的情况尽量避免吧。

 


等等...

引用  http://publications.gbdirect.co.uk/c_book/chapter8/sequence_points.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值