为什么 memset 采用 int 而不是 char?
为什么 memset
采用 int
作为第二个参数而不是 char
,而 wmemset
采用 wchar_t
而不是 long
或 long long
之类的东西?
Why does memset
take an int
as the second argument instead of a char
, whereas wmemset
takes a wchar_t
instead of something like long
or long long
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
memset
早于 C 语言添加函数原型的时间(相当早)。如果没有原型,您就无法将char
传递给function —— 当/如果你尝试时,当你传递它时,它会被提升为int
,并且函数接收的是一个int
。还值得注意的是,在 C 中(但在 C++ 中不是)像
'a'
这样的字符文字不具有类型char
——它类型为int
,因此您传递的内容通常都会以int
开头。本质上,它作为 char 启动并升级的唯一方法是传递一个char
变量。理论上,
memset
可能会被修改,以便它接收一个char
而不是int
,但这不太可能有任何好处,而且一个漂亮的破坏一些旧代码或其他代码的可能性很大。由于成本未知但可能相当高,而且几乎没有机会获得任何真正的好处,我想说将其更改为接收char
的机会正好位于“slim”和“没有任何”。memset
写入目标的值是其第二个参数转换为unsigned char
的值。memset
predates (by quite a bit) the addition of function prototypes to C. Without a prototype, you can't pass achar
to a function -- when/if you try, it'll be promoted toint
when you pass it, and what the function receives is anint
.It's also worth noting that in C, (but not in C++) a character literal like
'a'
does not have typechar
-- it has typeint
, so what you pass will usually start out as anint
anyway. Essentially the only way for it to start as a char and get promoted is if you pass achar
variable.In theory,
memset
could probably be modified so it receives achar
instead of anint
, but there's unlikely to be any benefit, and a pretty decent possibility of breaking some old code or other. With an unknown but potentially fairly high cost, and almost no chance of any real benefit, I'd say the chances of it being changed to receive achar
fall right on the line between "slim" and "none".The value
memset
writes into the destination is the value of its second argument converted to anunsigned char
.可能与
中的函数采用int
而不是chars
的原因相同。在大多数情况下在不同的平台上,
char
太小而无法单独压入堆栈,因此通常会压入最接近机器字长的类型,即int
。作为@Gui13 的评论指出,这样做也可以提高性能。
Probably the same reason why the functions in<ctypes.h>
takeints
and notchars
.On most platforms, a
char
is too small to be pushed on the stack by itself, so one usually pushes the type closest to the machine's word size, i.e.int
.As the link in @Gui13's comment points out, doing that also increases performance.
请参阅 Fred 的回答,这是出于性能原因。
在我这边,我尝试了这段代码:
它在 64 位 Mac 上给了我这个:
所以如你所见,只有最后一个字节被写入。我想这取决于架构(字节序)。
See fred's answer, it's for performance reasons.
On my side, I tried this code:
And it gives me this on a 64bits Mac:
So as you see, only the last byte gets written. I guess this is dependent on the architecture (endianness).