Bob Roberts
Bob Roberts

Reputation: 151

compiler doesn't recognize FILE* variable

(using Visual Studio 2012 C++ compiler)

The following compiles just fine:

FILE *filePointer = fopen("file.txt","wb");

But if I try to break it into two lines:

FILE *filePointer;
filePointer = fopen("file.txt","wb");

On the second line, the compiler doesn't recognize filePointer as a variable. I get errors like

Error:  this declaration has no storage class or type specifier

or

error C2040: 'filePointer' : 'int' differs in levels of indirection from 'FILE *'
error C2440: 'initializing' : cannot convert from 'FILE *' to 'int'

Why doesn't it remember that filePointer is a FILE*?

Upvotes: 1

Views: 130

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126203

This is a declaration:

FILE *filePointer = fopen("file.txt","wb");

This is also a declaration:

FILE *filePointer;

This, however, is a statement.

filePointer = fopen("file.txt","wb");

Declarations declare variables, and can appear at the top level (declaring a global variable), or within a function (declaring a local variable). Statements, on the other hand, can only appear in functions, and can access local or global variables. Only declarations can appear outside of functions, so if you put a statement there, the compiler will try to treat it as a declaration, and generally give you a confusing error message about something being wrong with a declaration, like the ones you quote.

Upvotes: 3

Related Questions