摘要:本文主要向大家介绍了 C/C++知识点之编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
本文主要向大家介绍了 C/C++知识点之编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配,通过具体的内容向大家展示,希望对大家学习C/C++知识点有所帮助。
在输出日志时 被 RUNLOG_DEBUG("%s,%d", para_int, para_str.c_str()) 坑过, 才知道 能校验 格式化字符串和 字段本身是否匹配 的重要性;
attribute format 该属性 可以给被声明的 函数 加上 类似 printf /scanf 的特征, 能用于 编译器检查 函数声明和时间调用参数直接的 格式化字符串是否 匹配; GNU CC需要使用 –Wall 才能使用
语法: format (archetype, string-index, first-to-check)
archetype : printf, scanf, strftime或strfmon, 表示按照那种风格进行检查
string-index: 传入参数的第几个参数是格式化字符串, 就是 "%s,%d" 的下标(从1 开始)
first-to-check: 指定从 函数的 第几个参数开始 校验
实例:
__attribute__((format(printf,m,n)))
m:第几个参数为格式化字符串(format string)
n:参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几.这里需要注意,有时函数参数里还有“隐身”的,如C++的类成员函数的第一个参数实际上是"隐身"的"this"指针;
#include <stdarg.h>
#include <string>
#include <stdio.h>
using namespace std;
#define mm_p(fmt, args...) myprint(fmt, args)
void myprint(const char *fmt,...) __attribute__((format(printf,1,2)));
void myprint(const char *fmt,...)
{
va_list ap;
va_start(ap, fmt);
vprintf(fmt,ap);
va_end(ap);
}
struct ss
{
public:
void pri(const char* fmt, ...) __attribute__((format(printf,2,3)))
{
}
};
int main()
{
mm_p("dfjkaj[%d][%s]\n",123,456);
myprint("dfjkaj[%d][%d]\n",123,456);
ss s;
s.pri("%s[%s", "dd",456);
}
g++ -Wall test_var.cpp -o test_var
test_var.cpp: In function 'int main()':
test_var.cpp:27: warning: format '%s' expects type 'char*', but argument 3 has type 'int'
test_var.cpp:31: warning: format '%s' expects type 'char*', but argument 4 has type 'int'
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号