Skip to content
Rain Hu's Workspace
Go back

[C++] 易錯題目收集

Rain Hu

C++ 易錯題目收集

1. bit-format expression

#include <bits/stdc++.h>
using namespace std;
int main(){
    unsigned int x = -1;
    int y = ~0;
    if (x==y)
        cout << "same";
    else
        cout << "not same";
    return 0;
}
same

2. 如何使 C(n,3) 正確且 n 的有效值最大?

return n*(n-1)/2*(n-2)/3;

3. register在C++中的用法

#include <bits/stdc++.h>
using namespace std;
int main(){
    register int i = 10;
    int *ptr = &i;
    cout << *ptr;
    return 0;
}
May generate Compilation Error

4. 有趣的 for loop 問題

int fun(){
    static int num = 16;
    return num--;
}
int main(){
    for(fun(); fun(); fun())
        cout << fun();
    return 0;
}
14 11 8 5 2

5. const 與 volatile

Pick the correct statemewnt for const and volatile keywords.
const and volatile are independent i.e. it's possible that a variable is defined as both const and volatile

6. operator priority

int main(){
    cout << (1 << 2 + 3 << 4);
    return 0
}
512

7. floating constant

Suppose a C++ program has floating constant 1.414, what's the best way to convert this as "float" data type?
`1.414f` or `1.414F`

8. array pointer

int main(){
    int arr[5];
    // Assume base address of arr is 2000 and size of integer is 32 bit
    printf(%u %u, arr+1, &arr+1);
    return 0;
}
2004 2020

9. initialize array

int main(){
    int a[][] = {{1,2},{3,4}};
    int i, j;
    for (int i = 0; i < 2; i++){
        for (int j = 0; j < 2; j++){
            printf("%d ", a[i][j]);
        }
    }
    return 0;
}
Compilation Error


Share this post on:

Previous
[Java] HashMap中的hashCode設計原理
Next
[C++] The C++ Standard Template Library(STL) - list, forward_list