File tree Expand file tree Collapse file tree 1 file changed +25
-23
lines changed
Expand file tree Collapse file tree 1 file changed +25
-23
lines changed Original file line number Diff line number Diff line change 22
33#define MAXLINE 1000
44
5+ /*
6+ * K&R Exercise 2-2: Write a loop equivalent to:
7+ * for (i = 0; i < lim - 1 && (c = getchar()) != '\n' && c != EOF; ++i)
8+ * s[i] = c;
9+ * without using && or ||.
10+ *
11+ * Note: Using * instead of && is unsafe because it doesn't short-circuit,
12+ * causing getchar() to be called even when the buffer is full or EOF is
13+ * reached.
14+ */
15+
516int main (void ) {
617 char s [MAXLINE ];
7-
8- // int i;
9- // int c;
10- // for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF);
11- // ++i)
12- // {
13- // s[i] = c;
14- // }
15-
18+ int c ;
1619 int i = 0 ;
17- int loop = 1 ;
18- while (loop ) {
19- char c = getchar ();
2020
21- if (i >= (MAXLINE - 1 ) || c == '\n' || c == EOF ) {
22- loop = 0 ;
21+ while (1 ) {
22+ if (i >= MAXLINE - 1 ) {
23+ break ;
2324 }
2425
25- s [i ++ ] = c ;
26+ c = getchar ();
27+
28+ if (c == '\n' ) {
29+ break ;
30+ } else if (c == EOF ) {
31+ break ;
32+ } else {
33+ s [i ++ ] = c ;
34+ }
2635 }
2736
2837 s [i ] = '\0' ;
2938
30- printf ("%s" , s );
39+ printf ("%s\n " , s );
3140
3241 return 0 ;
3342}
34-
35- // NOTE: The multiplication operation could work in this case because each
36- // expression is evaluated as a 1 or 0 (true or false), and a multiplication
37- // between expressions can have the value 1 only if all the expressions are
38- // true. However, the order of multiplication is not guaranteed to be sequenced
39- // as with logical operations. So, this is could cause serious problems
40- // depending on how the compiler deals with multiplication.
You can’t perform that action at this time.
0 commit comments