Date: December 7th 2012
Time: 09:00-11:00
Open book; turn off computer & mobile phone
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Size of a char array
#include <iostream>
using std::cout;
using std::endl;
int main()
{
char str[][18] = { "George Washington",
"John Adams",
"Thomas Jefferson",
"James Madison",
"James Monroe",
"John Quincy Adams"
};
cout << sizeof str[2] << endl;
return 0;
}
(10%) Determine whether the following code has syntax erros 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()
{
int data[2][4] = { {1, 3, 5, 7}, {2, 4, 6, 8} };
int* pnum = &data[0][2];
cout << *(pnum + 2) - *(pnum - 1) << endl;
return 0;
}
(10%) Determine whether the following code has syntax erros or not. If it is correct, predict its output. If it is incorrect, point out the mistake(s).
// Math function
#include <iostream>
#include <cmath>
int rnd(float x)
{ return static_cast<int>( floor(x + 0.5) ); }
int main()
{
std::cout << rnd(4.5) << std::endl;
return 0;
}
// Pass-by-reference
#include <stdio.h>
int strlen(char* &s)
{
char* p = s;
while (*p != '\0')
++p;
return p - s;
}
int main()
{
char* str = "Apple";
int n = strlen(str);
printf("The length of \"%s\" is %d.\n",
str, n);
return 0;
}