我如何 return C 中任何类型的值?
how can I return values of any type in C?
我需要获取一些在 C 代码中使用变量的日志;
例如来自以下代码:
int main(){
int a,b,c;
a=1;
b=1;
c= a==0||b==1
return 0;
}
我做:
int log(int v){
//print log
return v;
}
int main(){
int a,b,c;
a=1;
b=1;
c= log(a)==0||log(b)==1
return 0;
}
这个工作完美,但所有变量都是 int。
我如何为任何类型的变量执行此操作?
Log4c是你的朋友:
Log4c is a library of C for flexible logging to files, syslog and other destinations. It is modeled after the Log for Java library (http://jakarta.apache.org/log4j/), staying as close to their API as is reasonable. Here is a short introduction to Log4j which describes the API, and design rationale.
#include <stdio.h>
#define LOG(TYPE, STRING, VAR) \
(printf(STRING, VAR), (TYPE) VAR)
int main()
{
int j = 3;
double q = 2.3;
double s;
s = LOG(int, "j=%d\n", j) + LOG(double, "q=%lf\n", q);
LOG(double, "s=%lf\n", s);
}
j=3
q=2.300000
s=5.300000
一个警告:这会计算 VAR
表达式两次,因此它应该始终是常规变量的内容,而不是更复杂的表达式。您可以将对 printf
的调用替换为对使用可变参数的日志记录操作的调用。
how can i do this for variable of any type?
要根据各种类型切换代码,请使用 _Generic()
到 select 类型特定函数。
int log_int(int v) {
printf("(int %d)\n", v);
return !!v;
}
int log_double(double v) {
printf("(double %e)\n", v);
return !!v;
}
int log_char_ptr(char *v) {
printf("(str %s)\n", v);
return !!v;
}
#define mylog(X) _Generic((X), \
int: log_int, \
double: log_double, \
char *: log_char_ptr \
)(X)
现在代码只需要调用mylog(various_types)
.
int main(void) {
int i = 3;
double d = 4.0;
char *s = "5";
mylog(i)==0||mylog(d)==0||mylog(s)==0;
return 0;
}
输出
(int 3)
(double 4.000000e+00)
(str 5)
我需要获取一些在 C 代码中使用变量的日志;
例如来自以下代码:
int main(){
int a,b,c;
a=1;
b=1;
c= a==0||b==1
return 0;
}
我做:
int log(int v){
//print log
return v;
}
int main(){
int a,b,c;
a=1;
b=1;
c= log(a)==0||log(b)==1
return 0;
}
这个工作完美,但所有变量都是 int。
我如何为任何类型的变量执行此操作?
Log4c是你的朋友:
Log4c is a library of C for flexible logging to files, syslog and other destinations. It is modeled after the Log for Java library (http://jakarta.apache.org/log4j/), staying as close to their API as is reasonable. Here is a short introduction to Log4j which describes the API, and design rationale.
#include <stdio.h>
#define LOG(TYPE, STRING, VAR) \
(printf(STRING, VAR), (TYPE) VAR)
int main()
{
int j = 3;
double q = 2.3;
double s;
s = LOG(int, "j=%d\n", j) + LOG(double, "q=%lf\n", q);
LOG(double, "s=%lf\n", s);
}
j=3
q=2.300000
s=5.300000
一个警告:这会计算 VAR
表达式两次,因此它应该始终是常规变量的内容,而不是更复杂的表达式。您可以将对 printf
的调用替换为对使用可变参数的日志记录操作的调用。
how can i do this for variable of any type?
要根据各种类型切换代码,请使用 _Generic()
到 select 类型特定函数。
int log_int(int v) {
printf("(int %d)\n", v);
return !!v;
}
int log_double(double v) {
printf("(double %e)\n", v);
return !!v;
}
int log_char_ptr(char *v) {
printf("(str %s)\n", v);
return !!v;
}
#define mylog(X) _Generic((X), \
int: log_int, \
double: log_double, \
char *: log_char_ptr \
)(X)
现在代码只需要调用mylog(various_types)
.
int main(void) {
int i = 3;
double d = 4.0;
char *s = "5";
mylog(i)==0||mylog(d)==0||mylog(s)==0;
return 0;
}
输出
(int 3)
(double 4.000000e+00)
(str 5)