简体   繁体   中英

C++ EOF namespace

So, for curiosity, how come EOF doens't have a namespace defined? Why not ::EOF or std ::EOF ?

#include <cstdio>

while (std::scanf("%s", someStr) != ::EOF); // nope
while (std::scanf("%s", someStr) != std::EOF); // nope
while (std::scanf("%s", someStr) != EOF); // here we go

EOF is a preprocessor macro defined in <cstdio> (and in the C header <stdio.h> which is also usable from C++).

Preprocessor macros do text substitution on source code, before that code is actually compiled. As such, preprocessor macros are not names that can appear in any namespace.

This is different from function names declared in headers which can appear in namespaces.

In C, EOF was defined as a macro , using #define . It could possibly have been defined as const , except that it predates const .

For compatibility, this means it's also defined as a macro in C++. Something like:

#define EOF -1

If you know how #define works, you should see why ::EOF and std::EOF produce compiler errors. #define 'd macros are simple textual substitutions, so ::EOF expands to ::-1 and std::EOF expands to std::-1 , which are both invalid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM