7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

x++;

Last updated at Posted at 2013-04-29

単項演算子++について

C

hoge.c
# include <stdio.h>

void func(int a, int b, int c);

int main(void) {
	int x = 0;

	func(x++, x++, x++);

	return 0;
}

void func(int a, int b, int c) {
	printf("%d\n", a);
	printf("%d\n", b);
	printf("%d\n", c);
}

実行結果

C++も同様

$ cc hoge.c
$ ./a.out
2
1
0

次にJava

Hoge.java
public class Hoge {
	public static void main(String[] args) {
		int x = 0;

		func(x++, x++, x++);
	}

	static void func(int a, int b, int c) {
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
	}
}

実行結果

$ javac Hoge.java
$ java Hoge
0
1
2

PHP

hoge.php
<?php

$x = 0;

func($x++, $x++, $x++);

function func($a, $b, $c) {
	echo $a;
	echo $b;
	echo $c;
}
?>

実行結果

012

まとめ

  • ++演算子使える言語って意外と知らなかった。

Perlにも++があるらしい……。

  • Cは関数の引数を右から評価?

C言語の規格(ISO/IEC 9899:2011)を参照してみたところ、C11 のSection 6.5.2 に書いてあった。shunichi_sanさんのコメントのリンク先(該当箇所の日本語訳、解釈)によると、1行中に2回以上副作用を用いてはいけないらしい。

規格に違反するコードなため、値の評価は処理系依存ということのようだ。今回の実行環境cygwin+gccではたまたま右から評価される。

  • Java、phpはメソッド、関数の引数を左から評価?

The Java® Language Specification 15.12.4.2によると、Javaは引数の評価が必ず左から行われる。

phpのリファレンスマニュアルによると関数の引数は必ず左かららしい。

参考文献

7
7
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?