从数据类型中提取格式说明符?

时间:2017-06-20 20:04:04

标签: c types printf format-specifiers

是否可以通过编程方式为数据类型推断出格式说明符?例如,如果打印很长时间,它会自动执行以下操作:

printf("Vlaue of var is <fmt_spec> ", var);

我也觉得这样可以减少部分开发人员的错误,比如

printf("Name is %s",int_val); //Oops, int_val would be treated as an address

printf("Name is %s, DOB is",name,dob); // missed %d for dob

printf("Name is %s DOB is %d", name);//Missed printing DOB

据我所知,后两者确实有警告但如果错误抛出则不会更好,因为在大多数情况下会出现问题?或者我是否遗漏了某些内容或者是否已经建立了这样的构造?

2 个答案:

答案 0 :(得分:2)

  

数据类型的Deduce格式说明符?

没有

正如melpomene所说:

&#34;格式说明符不仅适用于类型。例如。 %o%xunsigned int; %e%f%g全部取double; %d%i%c全部取int。这就是为什么你不能(通常)从论证中推断出它们的原因。&#34;

重点是,如果存在这样的功能,那么它会推导出unsiged int%o%x吗?等等 。 。

关于某些案例是否应该发出警告或问题,您应该考虑如何在中进行投射,以及什么时候允许某些事情有意义。在GCC中,您当然可以将警告视为错误:

-Werror
Make all warnings into errors.

-Werror=
Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=switch makes -Wswitch warnings not be errors, even when -Werror is in effect.

The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)

Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.

您可以阅读here

答案 1 :(得分:1)

  

是否可以通过编程方式为数据类型推断出格式说明符?

不容易或直接使用printf(),但......

是的,使用_Generic限制选择的一组类型。

这可以通过各种方式完成并与*printf()一起使用,但是我发现了一种类似的打印数据方法,但没有在此示例中指定单独的格式说明符:
Formatted print without the need to specify type matching specifiers using _Generic
注意:这段代码有一个关于指针数学的编码孔,我已修补了 - 虽然没有发布。

GPrintf("Name is ", GP(name), " is ", GP(dob), GP_eol);

关键是使用_Generic(parameter)来引导选择用于将类型转换为文本的代码,方法是将宏GP(x)扩展为2部分:字符串和x。然后GPrintf()解释这些论点 这类似于@Michaël Roy的评论,但仍然使用C而不是C ++。

相关问题