Self-test 9:
Scope and separate compilation
-
What is the output of the following program?
#include <iostream> using namespace std; int Number; //global variable void Increment(int IncNum) { IncNum = IncNum + 3; cout << IncNum << endl; Number = Number + 1; } int main(void) { Number = 1; Increment(Number); cout << Number << endl; return 0; }Solution4.
2
-
What is the output of the following program?
#include <iostream> using namespace std; int Number; //global variable void Increment(int& IncNum) { IncNum = IncNum + 3; cout << IncNum << endl; Number = Number + 1; } int main(void) { Number = 1; Increment(Number); cout << Number << endl; return 0; }Solution4
5
-
What is the output of the following program?
#include <iostream> using namespace std; int Number; //global variable void Increment(int Number) { Number = Number + 1; cout << Number << endl; } int main(void) { Number = 1; Increment(Number); cout << Number << endl; return 0; }Solution2
1
-
What is the output of the following program?
#include <iostream> using namespace std; int A,B,C,D; void Two(int A, int B, int& D) { B = 21; D = 23; cout << A << " " << B << " " << C << " " << D << endl; } void One(int A, int B, int& C) { int D; A = 10; B = 11; C = 12; D = 13; cout << A << " " << B << " " << C << " " << D << endl; Two(A,B,C); } int main(void) { A = 1; B = 2; C = 3; D = 4; One(A,B,C); cout << A << " " << B << " " << C << " " << D << endl; Two(A,B,C); cout << A << " " << B << " " << C << " " << D << endl; return 0; }Solution10 11 12 13
10 21 23 23
1 2 23 4
1 21 23 23
1 2 23 4
-
Which of the following statements is NOT correct regarding separate compilation?
- Repeat the definitions of global constants.
- You must add the keyword extern for external variables.
- You must add the keyword extern for external functions.
- Repeat the function prototypes of external functions.
SolutionC. The keyword extern is optional because all C++ functions are global.
-
Given the definition of the struct
struct node { int value; node left; node right; };(a) What is the problem with the above definition? How to fix the bug?
(b) After fixing the bug, what is the output of the following code:
sizeof(node);Solution(a) Here, we have a recursion definition of node, which is not possible in C++. The correct way should be as follow:
struct node { int value; node *left; // pointer to the left node node *right; // pointer to the right node };(b) 12 bytes (in 32-bit machine) and 20 bytes (in 64-bit machines). sizeof computes number of bytes in a struct. In 32-bit machine, each address uses 4 bytes. In 64-bit machine (e.g. in our lab's linux machines), each address uses 8 bytes. So, sizeof(node) = sizeof(int) + 2*sizeof(node*). And, in a 32-bit machine, it is equal to 4 + 4*2 = 12 bytes; in a 64-bit machine, it is equal to 4 + 8*2 = 20 bytes.