diff --git a/02.html b/02.html index c7d5322f..0d45c9b1 100644 --- a/02.html +++ b/02.html @@ -819,6 +819,52 @@
printf("\110\x6F\154\x61"); // Used in a string literal. printf("%c\n", '\x21'); // Used in a character constant. // -> Hola!+
getchar
function reads one character from the process standard input and
+returns its value as an int
.
+Ctrl-D
in the
+terminal), it returns EOF
+EOF
is a define, usually set as -1
. That is why getchar
returns
+an int
instead of a char
as it needs an extra value for EOF
.getchar
needs #include <stdio.h>
+EOF
is part of <stdio>
, search for "getchar"
+here: https://pubs.opengroup.org/onlinepubs/9699919799
+It should work like this:
+$ cat /etc/passwd | ./a.out > passwd
+$ diff passwd /etc/passwd
+$ echo $?
+0
+
+if ((c = getchar()) == EOF)
+ return (0);
instead of:
+c = getchar();
+if (c == EOF)
+ return (0);
However, do not abuse it as you may create a hard to read code. Note the
+parentheses around the assignment. The =
operator has a lower priority than
+the ==
operator. If the parens are not used, the following would happen:
if (c = getchar() == EOF)
would be evaluated as:
if (c = (getchar() == EOF))
, meaning that c
would be either 0
or 1
based
+on whether we read a character or the terminal input is closed.
We will learn more about operator priority later in the semester.
+🔑 getchar.c
sizeof
operatorsizeof
operator computes the byte size of its argument which is either
@@ -960,52 +1006,6 @@ 🔑 ascii-hex.c
-getchar
function reads one character from the process standard input and
-returns its value as an int
.
-Ctrl-D
in the
-terminal), it returns EOF
-EOF
is a define, usually set as -1
. That is why getchar
returns
-an int
instead of a char
as it needs an extra value for EOF
.getchar
needs #include <stdio.h>
-EOF
is part of <stdio>
, search for "getchar"
-here: https://pubs.opengroup.org/onlinepubs/9699919799
-It should work like this:
-$ cat /etc/passwd | ./a.out > passwd
-$ diff passwd /etc/passwd
-$ echo $?
-0
-
-if ((c = getchar()) == EOF)
- return (0);
instead of:
-c = getchar();
-if (c == EOF)
- return (0);
However, do not abuse it as you may create a hard to read code. Note the
-parentheses around the assignment. The =
operator has a lower priority than
-the ==
operator. If the parens are not used, the following would happen:
if (c = getchar() == EOF)
would be evaluated as:
if (c = (getchar() == EOF))
, meaning that c
would be either 0
or 1
based
-on whether we read a character or the terminal input is closed.
We will learn more about operator priority later in the semester.
-🔑 getchar.c
Note that home assignments are entirely voluntary but writing code is the only way to learn a programming language.