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

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - 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