File tree Expand file tree Collapse file tree 1 file changed +11
-16
lines changed
Expand file tree Collapse file tree 1 file changed +11
-16
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 ];
718 int c ;
819 int i = 0 ;
920
10- // int i;
11- // int c;
12- // for (i = 0; (i < MAXLINE - 1) * ((c = getchar()) != '\n') * (c != EOF);
13- // ++i)
14- // {
15- // s[i] = c;
16- // }
17-
1821 while (1 ) {
1922 if (i >= MAXLINE - 1 ) {
2023 break ;
@@ -25,7 +28,6 @@ int main(void) {
2528 if (c == '\n' ) {
2629 break ;
2730 } else if (c == EOF ) {
28- printf ("\n" );
2931 break ;
3032 } else {
3133 s [i ++ ] = c ;
@@ -38,10 +40,3 @@ int main(void) {
3840
3941 return 0 ;
4042}
41-
42- // NOTE: The multiplication operation could work in this case because each
43- // expression is evaluated as a 1 or 0 (true or false), and a multiplication
44- // between expressions can have the value 1 only if all the expressions are
45- // true. However, the order of multiplication is not guaranteed to be sequenced
46- // as with logical operations. So, this is could cause serious problems
47- // depending on how the compiler deals with multiplication.
You can’t perform that action at this time.
0 commit comments