ProgrammingHardHCL · Tech Mahindra pattern
file1.c:
file1.c:
static int secret = 7;
int getSecret(void) { return secret; }file2.c:int getSecret(void);
int main(void) { printf("%d", getSecret()); }What happens when these are linked?- A. Linker error, same as accessing secret directly would be
- B. Prints 7 — functions default to external linkage, so getSecret is visible across files even though secret itself is hidden
- C. Compile error: getSecret must also be declared static
- D. Prints 0, secret's internal linkage blocks the accessor too
Correct answer: B. Prints 7 — functions default to external linkage, so getSecret is visible across files even though secret itself is hidden
static only hides the data object secret from other translation units. getSecret is declared without static, so it has the usual default external linkage and is perfectly visible to file2.c, which can call it to read the hidden value indirectly — exactly the encapsulation pattern static globals are used for.
More C Programming questions
- What is printed? c int a[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; int p = (int )a; printf("%d %d %d", (p + 5), ((a + 1) + 2), (a[2] +…
- Which identifier, even though declared at file scope, never has linkage at all in C?
- What can printf legally print here? c int i = 0; printf("%d %d %d", i++, i++, i++);
- What happens when this is compiled? c int compute(int x); static int compute(int x) { return x 2; } int main(void) { printf("%d"…
- What is printed? c int a[] = {10, 20, 30, 40, 50}; printf("%d", a[1, 3]);
- What can be said about this program? c int main(void) { int arr[5]; arr[5] = 10; printf("%d", arr[5]); }