國立暨南國際大學 109 學年度第二學期小考試卷

科目名稱:程式設計 開課系所:資訊工程 學系 考試日期 2021.3.18
系所別:
年級:
學號:
姓名:
考試時間 08:20-08:30
  1. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    /* Pass-by-Reference */
    #include <iostream>
    using std::cout;
    using std::endl;

    void swap(int a, int& b) {
        int temp = a;
        a = b;
        b = temp;
    }

    int main() {
        int x = 3, y = 18;
        swap(x, y);
        cout << x << y << endl;
        return 0;
    }

  2. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    /* Function Pointer */
    #include <iostream>
    using std::cout;
    using std::endl;

    int square(int n) { return n * n; }
    int cube(int n) { return n * n * n; }

    int main()
    {
        int *f(int) = square;
        cout << f(-5) << endl;
        f = cube;
        cout << f(-5) << endl;
        return 0;
    }


  3. (10%) Suppose you run the following code on an Intel x86 processor, where an unsigned integer is stored in 2-byte little-endian. Predict its output.
    /* void* and Little Endian */
    #include <iostream>
    using std::cout;
    using std::endl;

    int main()
    {
        short n = 0x4142;
        void* p = &n;
        char* p1 = static_cast<char*>(p);
        short* p2 = static_cast<short*>(p);
        cout << *p1 << *p2 << endl;
        // Can we "cout << *p" ?

        return 0;
    }


  4. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    /* Pointer Arithmetic */
    #include <iostream>
    using std::cout;
    using std::endl;

    int main()
    {
        unsigned short a[] = {1, 3, 5, 7, 9};
        cout << sizeof(a[0]);
        cout << a[1] << *(a+2) << endl;

        return 0;
    }