Note that there are some explanatory texts on larger screens.

plurals
  1. POgetint vague definition in k&r, weird behaviour of ungetch in it
    primarykey
    data
    text
    <p>I have a big problem understanding several lines from the following code (numbers marked in comments):</p> <p>First - the code of a loop that fills an array with the input data:</p> <pre><code>int n, array[SIZE], getint(int *); for (n = 0; n &lt; SIZE &amp;&amp; getint(&amp;array[n]) != EOF; n++) ; </code></pre> <p>Now the function definition:</p> <pre><code>/* getint: get next integer from input into *pn */ int getint(int *pn) { int c, sign; while (isspace(c = getch())) /* skip white space */ ; if (!isdigit(c) &amp;&amp; c != EOF &amp;&amp; c != '+' &amp;&amp; c != '-') { ungetch(c); /* [1] */ /* it is not a number */ return 0; /* [2] */ } sign = (c == '-') ? -1 : 1; if (c == '+' || c == '-') c = getch(); for (*pn = 0; isdigit(c); c = getch()) *pn = 10 * *pn + (c - '0'); [3] *pn *= sign; if (c != EOF) /* [4a] */ ungetch(c); /* [4b] */ return c; } #define BUFSIZE 100 char buf[BUFSIZE]; /* buffer for ungetch */ int bufp = 0; /* next free position in buf */ int getch(void) /* get a (possibly pushed-back) character */ { return (bufp &gt; 0) ? buf[--bufp] : getchar(); } void ungetch(int c) /* push character back on input */ { if(bufp &gt;= BUFSIZE) printf(" ungetch too many characters\n"); else buf[bufp++] = c; } </code></pre> <p>So:</p> <p>[1] I've read similar posts here, that taking back such an unwanted char somehow blocks the buffer, so that we need to clear it using another function. For me it's strange that is not included in K&amp;R and authors don't even mention the necessity to use it?</p> <p>[2] Why do we return 0? Does that stop the whole main() program? Or does it simply put 0 in an array ? ( getint(&amp;array[n] ) ?</p> <p>[3] Why do we need to implement such a formula to calculate "big numbers" ? Since that function just gets numbers one after the other (getchar not getword) and then create "big number" by means of several single integers.</p> <p>[4a][4b] Why does it ungetch if c != EOF? This condition is fulfilled most of the time, so we would end up with rejecting every inputted number?</p> <p>Thanks in advance for answering!</p>
    singulars
    1. This table or related slice is empty.
    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.
    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