Machine-translated by Google. Questions are authored in English.
Top

Discussion

extern int s;
int t;
static int u;

main()
{

}

Which of s, t and u are available to a function present in another file?

  • A.Only s
  • B.s and t
  • C.S, t, u
  • D.None

Answer: A

Correct answer: s and t

The question is one of linkage: which of these names can be referred to from a different translation unit.

extern int s; declares s with external linkage without defining it. The name refers to a single object shared across the whole program, defined in some other file, so a function in another file names the same s. Available.

int t; at file scope also has external linkage. It is a tentative definition: if nothing else in the file defines t, the compiler emits a definition initialised to zero. Another file can reach it by declaring extern int t;. Available.

static int u; at file scope is the exception. The static keyword here has nothing to do with lifetime - all three of these objects live for the whole run of the program - it sets internal linkage, confining the name to this translation unit. No other file can reach u, and another file may define its own unrelated u without a clash. Not available.

So s and t are visible outside the file and u is not. This record was keyed to “Only s”, which overlooks that a bare file-scope definition is external by default; the option reading “S & u” has been corrected to “s and t” and the key moved to it.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.