[英]Macros in C language
I am using this macro with gnu99 today but I want to change this macro to support -c99 according to my project requirements 我今天在gnu99中使用此宏,但我想根据我的项目要求更改此宏以支持-c99
#define STR(format, ...) ({static char str[256]; (void)snprintf(str, 256, format, ##__VA_ARGS__); str;})
I can convert the above macro to something like below but I dont know how to do with str in the end. 我可以将上面的宏转换为下面的内容,但最终我不知道如何使用str。
#define STR(format, ...)
do
{
static char str[256];
(void)snprintf(str, 256, format, ## __VA_ARGS__);
} while(0)
Can someone help me here? 有人可以帮我吗?
If you want an implementation of sprintf
that returns a string (instead of the character count), don't use a macro. 如果要实现返回字符串(而不是字符数)的sprintf
实现,请不要使用宏。 Write a short function with a cyclic buffer of short strings instead: 编写一个带有短字符串循环缓冲区的short函数:
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#define MAX_FMT 8
char *fmt(const char *format, ...)
{
static char buf[MAX_FMT][256];
static int nbuf;
va_list va;
nbuf++;
if (nbuf == MAX_FMT) nbuf = 0;
va_start(va, format);
vsnprintf(buf[nbuf], 256, format, va);
va_end(va);
return buf[nbuf];
}
int main()
{
printf("%40s\n%40s\n%40s\n",
fmt("%s: %d°C", "Copenhagen", 7),
fmt("%s: %d°C", "Paris", 10),
fmt("%s: %d°C", "Athens", 16));
return 0;
}
You need the functions of <stdarg.h>
here to implement your own printf
-like function. 您需要这里的<stdarg.h>
函数来实现自己的printf
的函数。 vsnprintf
is like snprintf
, except that it takes a va_list
. vsnprintf
类似于snprintf
,除了它需要一个va_list
。
A cyclic buffer of 8 static
char buffers allows you to return a string without allocation. 8个static
char缓冲区的循环缓冲区使您可以返回没有分配的字符串。 You can, of course, use at most 8 calls of fmt
at a time, eg inside one printf
call. 当然,您一次最多可以使用8个fmt
调用,例如在一个printf
调用中。
You are thinking far too complicated, just make it a single expression, and define the buffer once outside: 您认为过于复杂,只需使其成为一个表达式,然后在外部定义缓冲区即可:
#define STR_USE static char str[256]
#define STR(format, ...) (snprintf(str, sizeof str, format, ## __VA_ARGS__), str)
Use STR_USE;
使用STR_USE;
in any scope you might want to call STR
in, and use STR
as before. 在任何范围内,您可能都想调用STR
,并像以前一样使用STR
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.