惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
Vercel News
Vercel News
L
LangChain Blog
Google DeepMind News
Google DeepMind News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
About on SuperTechFans
博客园_首页
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
Apple Machine Learning Research
Apple Machine Learning Research
罗磊的独立博客
美团技术团队
V
V2EX

博客园 - shootingstars

硬件相关概念 我的Function C++概念网摘 Mifare 串行读取协议 韦根协议 学习C的可变参数 关于汇编程序调用各种C函数的例子 如何移植Java的类中的super到C++代码中 编译原理学习 关于标准库中的ptr_fun/binary_function/bind1st/bind2nd 使用python编写每日构建工具 boost::regex学习(5) - shootingstars - 博客园 boost::regex学习(4) - shootingstars - 博客园 boost::regex学习(3) boost::regex学习(2) 《世界大战》《变形金刚》观后感 boost::regex学习(1) boost::algorithm学习 五种迭代器
C的可变参数
shootingstars · 2010-01-08 · via 博客园 - shootingstars

C可以支持可变参数,所有才会有printf一类的神奇函数。问题是它是怎么实现的?其实看完了va_list/va_start等宏的定义后,才会猛然知道,原来它是这么的简单。其实就是C把所有变量压入一个堆栈,在函数中再按前面的format的指示从堆栈中取出对应的值而已。

相关网页:http://ipe.gzu.edu.cn/kszx/jsj/jyjl1/200910/33758.html

 上述网页中提到的一个问题是关于可变参数的传递问题,其实它并没有解决。(不可能把printf的所有解析过程重写一遍)

这个问题其实非常常见,比如我们的Log想支持可变参数的时候,就很有可能需要传递可变参数

Log(const char *format, ...)

问题是我们怎么把这个可变参数传递给printf之类的函数呢?

其实C有一个函数

int vsnprintf(char *str, size_t size, const char *format, va_list args);

这个函数支持这种类型va_list args

我们可以这样写这个函数


代码

 Log(const char *format, ...)
{
    
char buf[512];
    va_list args;
    va_start(args, format);
    
int len = vsnprintf(buf, sizeof(buf), format, args);
    
// 你可以放一些printf之类的函数,或者直接写文件等等...
    va_end(args);

注意:Windows CRT的名字为_vsnprintf