In C++ (default pointer argument bound to a static global), what is printed? Note that a local variable named b shadows the global, but the call passes both pointers explicitly.
#include
static int b = 0;
void DisplayData(int *x, int *y = &b)
{
cout << *x << " " << *y;
}
int main()
{
int a = 10, b = 20;
DisplayData(&a, &b);
return 0;
}
-
AThe program will print the output 10 20.
-
BThe program will print the output 10 0.
-
CThe program will print the output 10 garbage.
-
DThe program will report compile time error.
Answer
Correct Answer: The program will print the output 10 20.
Explanation
Introduction / Context: This checks understanding of default arguments captured at compile time, name shadowing between a file-scope static and a local variable, and what happens when the caller supplies both parameters explicitly anyway.
Given Data / Assumptions:
- Global (file-scope)
static int b = 0initializes the default foryas&b. maindeclares a localb = 20which shadows the global name in that scope.- Call site explicitly passes
&aand&b(the local one).
Concept / Approach: Because the call provides y, the default is not used. Therefore, dereferencing *x yields 10 and *y yields 20 from the local b. The existence of the global static only matters if the second argument were omitted.
Step-by-Step Solution:
x → &a → *x = 10 y → &(local b) → *y = 20 Output: "10 20"Verification / Alternative check: If you called DisplayData(&a) with no second argument, the output would be "10 0" due to the default binding to the file-scope static b.
Why Other Options Are Wrong:
- 10 0: Would occur only when omitting the second argument.
- Garbage / compile error: The code is valid and pointers are initialized.
Common Pitfalls: Confusing which b is referenced when both a global and local exist; explicit argument selection wins here.
Final Answer: The program will print the output 10 20.