compile-fan
compile-fan

Reputation: 17625

What does (char *)0 mean in C?

if ( fgets( line, sizeof(line), stdin ) == (char*) 0 )...

I don't understand what this line does, anyone knows?

Upvotes: 5

Views: 9929

Answers (6)

Felice Pollano
Felice Pollano

Reputation: 33262

It means a null pointer to char. It would be the same if you replace the (char*)0 with NULL. In this particular case it is checking if there is nothing more to read from the stdin. I think is just a way to be cryptic and showing some spectacular and beautiful features. If you replace it with a NULL you gain in readability without changing the semantic.

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 822

(char*) 0

Is not a null character, but a pointer to a character at address 0.

A character containing the value 0 would be:

(char) 0

Upvotes: 4

Jamie
Jamie

Reputation: 3931

(char*)0 creates the "null" pointer. So you are seeing if the value of fgets is null.

The documentation for fgets states that it returns null when there is an error or you have reached end of file.

The full statement appears to be checking if you are at the end of the file, and if so breaking out (though that's a guess).

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613232

That's a rather odd way of writing a test for the return of a null pointer which indicates an error in fgets().

I'd write it like this:

if (!fgets(line, sizeof(line), stdin))

Upvotes: 4

Joe
Joe

Reputation: 57179

It is simply checking the results of fgets for null character pointer.

According to cplusplus.com

Return Value

On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned.

If an error occurs, a null pointer is returned.

Use either ferror or feof to check whether an error happened or the End-of-File was reached.

Upvotes: -2

Fox32
Fox32

Reputation: 13560

The line checks if fgets return 0. The cast to char* is only to match the return type of fgets:

char * fgets ( char * str, int num, FILE * stream );

But 0 is implicit converted to char* if you remove it.

If you need more information on fgets look here

Upvotes: 1

Related Questions