- (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;
}
- (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;
}
- (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;
}
- (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;
}