我通过自学成才学过C,我认为%ld
可以用于更长的数字,我不知道为什么有%d
,而对于较短的%hd
,if let tempArray = json as? [[String: Any]] {
self.newsArray = tempArray
self.tableView.reloadData()
}
1}},或者类似的?
我还想知道C说明符是如何工作的,为什么我们需要不同范围的数字数据类型的不同说明符,因为每种数据类型都限制了范围?
答案 0 :(得分:1)
从外观上看,你在谈论打印功能?或者其他一些采用类似参数的函数。
它与原始类型有关,例如:
int
可以包含小于16位的数字。
其中long
可以容纳32位。
然后有一个long long
可以容纳64位。
这一切都取决于你正在使用的原语,很容易找到一个原语所拥有的位数。您还必须在使用它们的时间和地点时要小心,因为用户可能没有足够强大的计算机来运行它。还有一个事实是某些版本的C可能没有特定的原语,这可能会降低年龄甚至优化修改后的C系统。
答案 1 :(得分:1)
考虑printf(const char *format, ...)
在格式和任意数量的值之后采用任意类型。 int
占用的空间通常比long long
占用的空间少。
printf()
使用format
来确定后面的参数。如果说明符与传递的类型不匹配,则为未定义的行为。
long long ll = 12345678;
int i = 4321;
printf("%lld %d\n", ll, i); // Format matches the type and count of arguments passed.
// Result: values printed as text as expected
printf("%d %d %d\n", ll, i); // Format mis-matches the type and count of arguments
// Result: undefined behavior
"%hd"
"%hdd"
涉及另一种机制。很久以前,C决定在使用short
和signed char
之类的小类时,在进一步处理之前,他们会首先通过整数提升到int
(存在一些例外)。因此对于像printf()
这样的函数,当传递short
时,该值首先转换为int
。 printf()
无法知道其收到的int
最初是int
还是short
。在这种情况下,以下是可以的。
int i = 4321;
short s = 321;
printf("%hd %d\n", i, i); // Format matches the promoted type
printf("%hd %d\n", s, s); // Format matches the promoted type
当printf()
遇到"%hd"
时,它会收到int
,但会在打印前在内部将int
值转换为short
值。