C99 printf格式化和C ++ 11用户定义文字 [英] C99 printf formatters vs C++11 user-defined-literals

查看:271
本文介绍了C99 printf格式化和C ++ 11用户定义文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc,char **argv)
{
   uint64_t val=1234567890;
   printf("%"PRId64"\n",val);
   exit(0);
}

适用于 C99 C ++ 03 C ++ 11根据GCC 4.5 ,但在根据GCC 4.7.1 的C ++ 11中失败。在 PRId64 之前添加一个空格让GCC 4.7.1编译它。

Works for C99, C++03, C++11 according to GCC 4.5, but fails on C++11 according to GCC 4.7.1. Adding a space before PRId64 lets GCC 4.7.1 compile it.

哪一个是正确的?

推荐答案

gcc 4.7.1是正确的。根据标准,

gcc 4.7.1 is correct. According to the standard,


c ++ 11

1 - 翻译语法规则中的优先级由以下
阶段指定。 [...] 0047
3.源文件被分解为预处理令牌(2.5)和空格字符序列
(包括注释)。 [...]

1 - The precedence among the syntax rules of translation is specified by the following phases. [...]
3. The source file is decomposed into preprocessing tokens (2.5) and sequences of white-space characters (including comments). [...]
4. Preprocessing directives are executed, macro invocations are expanded, [...]

每个 2.5预处理标记[lex.pptoken] ,用户定义的字符串文字是一个预处理标记生成:

And per 2.5 Preprocessing tokens [lex.pptoken], user-defined-string-literal is a preprocessing token production:


2.14.8用户定义的文字[lex.ext]



用户定义的字符串:

    string-literal ud-suffix

ud-suffix

   

因此, PRId64 是无关的,因为%PRId64 已经被解析为单个用户定义的字符串文字 em> string-literal ud-suffix PRId64

So the phase-4 macro expansion of PRId64 is irrelevant, because "%"PRId64 has already been parsed as a single user-defined-string-literal preprocessing token consisting of string-literal "%" and ud-suffix PRId64.

哦,这将是真棒;每个人都必须更改

Oh, this is going to be awesome; everyone will have to change

printf("%"PRId64"\n", val);

printf("%" PRId64"\n", val);     // note extra space






gcc和clang已同意将用户定义的字符串文字作为两个单独的标记(根据非完备性标准)处理在后缀中没有前导下划线,参见 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52538 所以对于未来版本的gcc(4.8分支,我认为)现有的代码将再次工作。


However! gcc and clang have agreed to treat user-defined string literals without a leading underscore on the suffix as two separate tokens (per the non well formedness criterion), see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52538 so for future versions of gcc (4.8 branch, I think) existing code will work again.

这篇关于C99 printf格式化和C ++ 11用户定义文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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