CとC++の非互換性:文字リテラルのサイズ

最近知った豆知識です。


CとC++で、以下のコードを実行したときの結果は異なります。

printf( "%d", sizeof('A') );



実行してみると、Cでは4が表示され、C++だと1となります。

理由は、C言語の仕様上文字リテラルはintとみなされ、C++ではcharとみなされるから。


以下、仕様より

An integer character constant has type int. 
 
The value of an integer character constant containing a single character 
that maps to a single-byte execution character is the numerical value of 
the representation of the mapped character interpreted as an integer.


ANSI C section6.4.4.4



A character literal is one or more characters enclosed in single quotes, as in 'x'


Programming languages C++(ISO/IEC 14882) 2.13.2


ちなみに、C言語では”文字定数(character constant)、C++では文字リテラル(character literal)。

関連記事

コメントを残す

メールアドレスが公開されることはありません。