-
Notifications
You must be signed in to change notification settings - Fork 0
library function
yuyabu edited this page Jul 3, 2019
·
1 revision
使われているライブラリ関数などをまとめます
ただ写経しているだけだと勉強にならないと思うでの、使われているライブラリ関数などを調べてメモしています。 主にmanコマンドを使っています。
最初の電卓をコンパイルするコードで登場
#include <stdlib.h>
long int strtol(const char *nptr, char **endptr, int base);
マニュアルによると文字列を指定したbaseのN進数のlong int,long long intに変換する関数らしい。
- strtolはString to longの略称か?
The strtol() function converts the initial part of the string in nptr to a long integer
value according to the given base, which must be between 2 and 36 inclusive, or be the
special value 0.
nptrを数値として読めるまで読んだ後、(数値でない値を読んだ最初のアドレスを)endptrに格納するらしい。
If endptr is not NULL, strtol() stores the address of the first invalid character in
*endptr. If there were no digits at all, strtol() stores the original value of nptr in
*endptr (and returns 0). In particular, if *nptr is not '\0' but **endptr is '\0' on
return, the entire string is valid.
ちょっとややこしいけど、書中では以下のように利用されている。
printf(" mov rax, %ld\n", strtol(p, &p, 10));
・・・
while (*p) {
if (*p == '+') {
p++;
printf(" add rax, %ld\n", strtol(p, &p, 10));
continue;
}
if (*p == '-') {
p++;
printf(" sub rax, %ld\n", strtol(p, &p, 10));
continue;
}
fprintf(stderr, "予期しない文字です: '%c'\n", *p);
return 1;
}
オペレーター(+/-)を読んだ後のアセンブリにオペランドを埋め込む際に利用している。 記号 数値 記号 数値・・・という順番で入力されるという前提なんだろうか。