Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing int for character types when comparing with EOF
    primarykey
    data
    text
    <p>Quoting from Kernighan and Ritchie's 'The C Programming Language' Page 16 - </p> <pre><code>#include&lt;stdio.h&gt; main() { int c; c = getchar(); while(c!=EOF) { putchar(c); c = getchar(); } getchar(); return 0; } </code></pre> <p>"The type <code>char</code> is specifically meant for storing such character data, but any integer type can be used. We used <code>int</code> for a subtle but important reason. The problem is distinguishing the end of the input from valid data. The solution is that <code>getchar</code> returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called <code>EOF</code>, for "end of file". We must declare <code>c</code> to be a type big enough to hold any value that <code>getchar</code> returns. We can't use <code>char</code> since <code>c</code> must be big enough to hold <code>EOF</code> in addition to any possible <code>char</code>. Therefore we use <code>int</code>.".</p> <p>I looked up in stdio.h, it says <code>#define EOF (-1)</code></p> <p>The book conclusively states that <code>char</code> cannot be used whereas this program "works just fine" (See EDIT) with <code>c</code> as <code>char</code> data type as well. What is going on? Can anyone explain in terms of bits and signed values? </p> <p><strong>EDIT:</strong><br> As Oli mentioned in the answer, the program cannot distinguish between <code>EOF</code> and <code>255</code>. So it will not work fine. I want to know what's happening - Are you saying that when we do the comparison c!=EOF, the EOF value gets cast to a char value = 255 (11111111 in binary; i.e. the bits 0 through 7 of EOF when written in 2's complement notation)? </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload