The First C Program
History
...
Program
main Function
- A program exits successfully if and only if its main function returns
0.- If the return type is compatible with
intand control reaches the terminating}, the value returned to the environment is the same as if executingreturn 0;
- If the return type is compatible with
printf & scanf
#include <stdio.h>printf- Will
%dconvert? More below at
- Will
scanf%?: type of variable- NOTE:
%dwill skip any leading whitespaces- "whitespace": space, newline || return(
\n/\r), tab(\t), etc- Standard:
whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling isspace in a loop). Note that there is no difference between "\n" , "" , "\t\t" , or other whitespace in the format string. - More below at [[#Note about format string in
scanf]]
- Standard:
- "whitespace": space, newline || return(
Note about format string in scanf
TLDR
%d: Reads nums when non-whitespace char occurred\n: Reads newline and discard any whitespace char after it (or until non-whitespace char occurred)
According to the ref:
- The format of the number is the same as expected by
strtolwith the value 10 for thebaseargument.strolis a function to convertstringtolong int- ref: Interprets an integer value in a byte string pointed to by str
- How does
strolparse a string?- Discards any whitespace characters (as identified by calling isspace ) until the first non-whitespace character is found, then...
Case I: "%d\n%d\n"
// Input #0
1 // Enter
2 // Enter
// Enter (Did not stop, still waiting)
3 // Enter
// Stopped, received 1, 2
// Input #1
1 2// Enter
// Enter (Did not stop, still waiting)
3 //Enter
// Stopped, received 1, 2
// Input #2
1 2 3//Enter
// Stopped, received 1, 2
Summary: It will wait you untill you've entered a non-whitespace character
Case II: %d\n%d
Case III: %d%d
WHY?
%d: Reads nums when non-whitespace char occurred\n: Reads newline and discard any whitespace char after it (or until non-whitespace char occurred)
So
- Case I
- Read
1\n\nmarks the end of%d, soscanfaccpeted1and gave\nback to input buffer
- Read
\n(or many other whitespace charaters)\nmeets the need of\n, andscanfaccepted it and wait until another whitespace char occurred(2)
- Read
2\n2is a non-whitespace charater, marks the end of\n2\nmeets the need of the 2nd%d, and give\nback to buffer again
- Read
\n*n\nmeets the need of\n, wait non-whitespace charater
- Read
3- Here
3is a non-whitespace charater, it marks the end of\n, stop.
- Here
- Read
Note about printf
- print
%ldwith%d?
// Case I:
double pi = 3.14;
printf("%d\n", pi);
// Output: 1374389535
// Case II:
double pi = 3.14;
int pi_int = pi; // pi_int 值为 3
printf("%d\n", pi_int);
// Output: 3
这里的 double 为什么这么奇怪
conversion specifier 与对应的变量类型不匹配是 undefined behavior,不是每个平台、环境都会得到这个输出
但是我们来理解一下:
在 x86-64 clang 的编译环境下,3.14 将会按照IEEE 754标准进行存储
二进制表示为:
如果输出为 long long ,即可看到对应的数字:4614253070214989087