Udar
Udar

Reputation: 85

Initialising a c with int as EOF and then using it for getchar()?

The title pretty much says it all. I have this code for the homework (sent by the lecturer) which is for a spellchecker and I do not see the reason for c being an int initialized with EOF and then using it for getchar()? This is new to me, thank you! (I do not have anything inside the while because it is my assignment to put code there and I got stuck at the question above)

 int c = EOF;
 while ((c = getchar()) && c != EOF) {

  } 

EDIT: I was told the EOF is just so that it doesn't enter the while if there is no input but doesn't make sense to me since if c doesn't use getchar the while is still unused

Upvotes: 0

Views: 132

Answers (1)

chux
chux

Reputation: 153468

The initialization is not functionally required.

It has the nice attribute of having c with an initialized value. Useful for debugging and avoiding otherwise uninitialized object errors. But in this case, code could have been int c = 0;, int c;, int c = EOF;, .... with no functional difference.

int c = EOF;
while ((c = getchar()) && c != EOF) {
  ;
}

OP: I was told the EOF is just so that it doesn't enter the while if there is no input but doesn't make sense to me since if c doesn't use getchar the while is still unused

If there is no input, c = getchar() will assigned EOF to c, overwriting the EOF initialization of int c = EOF;. In this case, the loop body is not entered even without initialization.


Now the debate can move to "what should be done" as the initialization is not functionally required. This and many like issues are best resolved by your group's coding standards. Lacking a group standard, follow the lead of your customer (professor?). Lacking that lead, go for what is simply: int c;


while ((c = getchar()) && c != EOF) { is an anti-pattern as it stops the loop when end-of-file occurs or if a null character is read. @wildplasser The below is more common, but selection depends on your coding goals.

while ((c = getchar()) != EOF) {

OP: So far I've only initialized variables with char when using getchar(), thought it has to be a char.

int getchar(void); typically returns 257 different values, [0...UCHAR_MAX] and EOF. Saving that into a char loses information. Use int.

Upvotes: 0

Related Questions