2012年4月16日月曜日

開発環境

『実践プログラミング 第3版』 (Steve Oualline (著)、 望月 康司 (監修) (翻訳)、 谷口 功 (翻訳)、 オライリー・ジャパン、1998年、ISBN978-4900900646) の10章(Cプリプロセッサ)10.1(#define文)設問10-1を解いてみる。

設問10-1.

ぷりp路切瑳を使用したdefine文のALL_PARTSの値は2つの和の値ではなくFIRST_PART + LAST_PARTそのままで、それがCのコードのプログラムに渡されるから加算と乗算の演算の優先順位が意図とは違うものとなり、回答も意図とは違う結果になってしまう。

修正

コード(TextWrangler)

#include <stdio.h>

#define FIRST_PART  7
#define LAST_PART  5
#define ALL_PARTS  (FIRST_PART + LAST_PART)

int main(){
  printf("The square of all the parts is %d\n",
          ALL_PARTS * ALL_PARTS);
  return (0);
}

入出力結果(Terminal)

$ cc -o sample sample.c
$ ./sample
The square of all the parts is 144
$

あるいは、

コード(TextWrangler)

#include <stdio.h>

#define FIRST_PART  7
#define LAST_PART  5
#define ALL_PARTS  FIRST_PART + LAST_PART

int main(){
  printf("The square of all the parts is %d\n",
          (ALL_PARTS) * (ALL_PARTS));
  return (0);
}

入出力結果(Terminal)

$ cc -o sample sample.c
$ ./sample
The square of all the parts is 144

1個目の修正の仕方の方が分かりやすいかも。。

0 コメント:

コメントを投稿