1

if次のようなマクロにtypedef があります。

#ifdef BLA_BLA
typedef int typeA
#elseif 
typedef double tyeA
#endif
printf("%d" , a); printf("%l" , a);

この場合のprintfを書くときの最善のアプローチは何ですか? (%dまたは%l)。

マクロでも固定文字列を定義できることはわかっています。しかし、それは最善の方法ですか?

4

4 に答える 4

7

マクロを使用して、フォーマット文字列も定義します。

#ifdef BLA_BLA
typedef int typeA;
#define FORMAT "%d"
#elseif 
typedef double typeA;
#define FORMAT "%f"
#endif

...
typeA a = ...;
printf("Hello " FORMAT " there", a); printf(FORMAT , a);
于 2012-05-17T19:11:28.890 に答える
2

本当に型を整数または浮動小数点として定義したいですか?どちらも数値ですが、動作がさまざまな点で非常に異なるため、どちらの場合でも正しく機能するコードを作成するのは困難です。

多くの場合、両方の可能なタイプの範囲をカバーするのに十分な幅のタイプに変換できます。簡単な例:

#include <stdio.h>

#ifdef BLA_BLA
typedef int num_type;
#else
typedef long num_type;
#endif

int main(void) {
    num_type x = 42;
    printf("x = %ld\n", (long)x);
    return 0;
}

より一般的には、またはに変換でき、intmax_tまたはuintmax_tで定義され、<stdint.h>または<inttypes.h>を使用して"%jd""%ju"それぞれに変換できます。

すべてをに変換することでほぼ同じことができますがlong double、大きな整数値の場合は精度が低下する可能性があります。

于 2012-05-17T21:01:51.840 に答える
0

私だったら、typeA引数をprintf直接渡しません。値の文字列表現を返す別の関数を作成し、typeAその文字列をprintf(またはそれを表示するために必要な他の関数に) 渡します。

char *formatTypeA(typeA val, char *buf, size_t len)
{
  #ifdef BLA_BLA
  #define FORMATCHAR d
  #else
  #define FORMATCHAR f
  #endif

  char formatStr[SIZE]; // where SIZE is large enough to handle the longest
                        // possible size_t value plus "%" plus the format
                        // character plus the 0 terminator
  sprintf(formatStr, "%%%zu" FORMATCHAR, len - 1); 
  sprintf(buf, formatStr, val);
  return buf;
}

int main(void)
{
  typeA foo;
  char output[10];
  ...
  printf("foo = %s\n", formatTypeA(foo, output, sizeof output));
  ...
}

おそらくもっと良い方法があります。

編集

これが、私が typedef をあまり使用しない傾向がある理由の 1 つです。表現が重要な場合 (この場合のように)、その情報を使用している人からその情報を隠したくありません。

于 2012-05-17T21:08:00.283 に答える
-1

さらに別の方法 - 短いヘルパー関数を定義して、コード全体に ifdef を振りかける必要がないようにします。

#ifdef BLA_BLA
typedef int typeA
#else
typedef double typeA
#endif

inline void print_typeA(const typeA val) {
#ifdef BLA_BLA 
  printf("%d" , val); 
#else
  printf("%e" , val);
#endif
}

somefunc()
{ typeA xyz;

  print_typeA(xyz);
}
于 2012-05-17T20:53:37.810 に答える