Portability in C/C++

以下的 code 都有移植性的問題。

n = (getchar() << 8)  |  getchar();
ptr[count] = name[++count];
printf("%c %c\n", getchar(), getchar());
printf("%f %s\n", log(-1.23), strerror(errno));
char c; /* should be int */
c = getchar();

  • sizeof is a compile-time operator that returns the size in bytes of the variable or parenthesized type-specifier that it precedes [http://en.wikipedia.org/wiki/Sizeof]
  • sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(float) <= sizeof(double)
  • 1 <= sizeof(char)
  • 2 <= sizeof(short)
  • 2 <= sizeof(int)
  • 4 <= sizeof(4)
  • sizeof 在語言層面的陷阱
    • sizeof('J') vs. sizeof(char)
      • C++ 中 sizeof('J') 等同於 sizeof(char),所以我們看到輸出 1
      • 但是對於 C 語言來說,有著 default to int 的語意,所以等同於計算 sizeof(int)
      • 而 C# 與 C++ 對此有類似的表現
    • size of structure
      • C 中 ,空的 structure ,空間為 0
      • C++ 中,任何空的 structure ,空間至少為 1,除非是 base class (pure virtual)

c
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License