Skip to content

Commit cfd1076

Browse files
committed
Refactor loop implementation to avoid logical operators
- Added comments to clarify the approach and potential pitfalls of using multiplication instead of logical operators.
1 parent c8cbf8a commit cfd1076

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

chapter_2/exercise_2_02/loop.c

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,32 @@
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+
516
int 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;
2124
}
2225

2326
c = getchar();
24-
27+
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.

0 commit comments

Comments
 (0)