如果有%ld或甚至%lld,我们为什么要使用%d甚至%hd?

时间:2016-12-22 05:13:12

标签: c types

我通过自学成才学过C,我认为%ld可以用于更长的数字,我不知道为什么有%d,而对于较短的%hdif let tempArray = json as? [[String: Any]] { self.newsArray = tempArray self.tableView.reloadData() } 1}},或者类似的?

我还想知道C说明符是如何工作的,为什么我们需要不同范围的数字数据类型的不同说明符,因为每种数据类型都限制了范围?

2 个答案:

答案 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决定在使用shortsigned char之类的小类时,在进一步处理之前,他们会首先通过整数提升int(存在一些例外)。因此对于像printf()这样的函数,当传递short时,该值首先转换为intprintf()无法知道其收到的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值。