0%

Some misleading concept in C/C++

看到濟濟篇文章的總結,寫起來,免得忘了。

do-while & continue

以下這段Code應該一堆人猜錯

1
2
3
4
5
int i = 0;
do {
std::cout << i << std::endl;
if (i < 5) continue;
} while (i++);

continue會跳到邏輯判斷的地方,而不是Block的最前端。

sizeof

sizeof是compile-time的operator,所以以下這段code的結果會是4 0

1
2
3
int i = 0;
std::cout << sizeof(i++) << std::endl;
std::cout << i << std::endl;

另外sizeof在不同的地方會有不同的表現

1
2
3
4
5
6
7
8
9
int arr[SIZE][SIZE][SIZE];
void print_sizeof(int a[SIZE][SIZE][SIZE])
{
std::cout << sizeof(a) << std::endl; // 4
std::cout << sizeof(a[0]) << std::endl; // 400
std::cout << sizeof(a[0][0]) << std::endl; // 40
}
std::cout << sizeof(arr) << std::endl; // 4000
print_sizeof(arr);

裡面最令人驚奇的是print_sizeof中的第一個輸出值是4,因為第一維的index是pointer。

Static class variable in class

1
2
3
4
5
6
7
8
9
class A {
public:
A() { cout << "A::A" << endl; }
};
class B {
static A a;
public:
B() { cout << "B::B" << endl; }
};

這邊的輸出結果沒有呼叫A的Constructor,因為a只宣告沒定義。
需要加上

1
A B::a;

如果我們沒有加上定義,這樣子是沒有問題的。

1
2
3
4
5
6
7
8
class B {
static A a;
public:
B() { cout << "B::B" << endl; }
static A getA() { return a; }
};
B b;
A a = b.getA();

因為A是個empty class所以就算沒定義也沒問題,如果不是的話就會出現編譯錯誤。

NULL pointer to an object

這段Code沒有問題

1
2
3
4
5
6
7
class A {
int x;
public:
void print() { cout << "A" << endl; }
};
A *pA = nullptr;
pA->print();

因為member function不涉及這物件的屬性任何操作,因此什麼都沒發生。