C ++ EOF namespace

So, for curiosity, why doesn't EOF have a namespace? 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

      

+3


source to share


2 answers


EOF

is a preprocessor macro defined in <cstdio>

(and in the C header <stdio.h>

, which can also be used from C ++).

Preprocessor macros replace text in the source code before that code is compiled. Thus, preprocessor macros are not names that can appear in any namespace.



This differs from function names declared in headers, which can appear in namespaces.

+2


source


In C, EOF was defined as a macro using #define

. It may have been identified as const

, except that it precedes const

.

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



#define EOF -1

      

If you know how it works #define

, you should see why ::EOF

and std::EOF

generate compiler errors. #define

'd macros are simple text substitutions, so it ::EOF

expands to ::-1

and std::EOF

expands to std::-1

, which are invalid.

+2


source







All Articles