为什么在 msvc++ 中我们有 _snprintf 而其他编译器允许 snprintf [英] Why in msvc++ we have _snprintf while other compilers allows snprintf

查看:73
本文介绍了为什么在 msvc++ 中我们有 _snprintf 而其他编译器允许 snprintf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

_"是什么意思?微软为什么在开头加上这个标志?

What "_" means? Why Microsoft adds this mark at the beginning?

推荐答案

全局命名空间中以 _ 开头的标识符是为实现保留的._snprintf 只是实现(Visual Studio)提供的一个函数.至于其原理,Visual Studio 实现了 C89,而 snprintf 是后来的 C99 标准的一部分.

Identifiers in the global namespace starting with _ are reserved for the implementation. _snprintf is just a function that the implementation (Visual Studio) has provided. As to the rationale for that, Visual Studio implements C89, and snprintf is part of a later C99 standard.

除此之外,这两个函数的语义在返回类型上是不同的,在snprintf中始终是格式化字符串所占用的字符数(无论缓冲区是否有足够的空间,而如果缓冲区空间不足,_snprintf 将返回一个负数.

Besides that, the semantics of both functions are different in the return type, which in snprintf is always the number of characters that the formatted string takes (whether there was enough space in the buffer or not, while _snprintf will return a negative number if there is not enough space in the buffer.

也就是说,分配一个足够大的缓冲区,您可以执行以下操作:

That is, to allocate a buffer just large enough for the output you can do:

int size = snprintf( 0, 0, "%s %d\n", str, i );
char * buffer = malloc( size+1 );
snprintf( buffer, size+1, "%s %d\n", str, i );

您不能使用 _snprintf 来做到这一点,因为该函数返回的唯一信息是当前大小不够.

You cannot do that with _snprintf as the only information that the function yields back is that the current size is not enough.

这篇关于为什么在 msvc++ 中我们有 _snprintf 而其他编译器允许 snprintf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆