gpt4 book ai didi

c - 作业是关于使用宏的

转载 作者:行者123 更新时间:2023-12-02 18:42:08 25 4
gpt4 key购买 nike

这个问题是关于我的作业的。
这个主题需要使用如下:

#define GENERIC_MAX(type)\
type type##_max(type x, type y)\
{\
return x > y ? x : y;\
}

题目内容是让这段代码正常运行:

#include <stdio.h>

GenerateShowValueFunc(double)
GenerateShowValueFunc(int)

int main()
{

double i = 5.2;
int j = 3;

showValue_double(i);
showValue_int(j);

}

运行结果是这样的:

i=5.2000
j=3

这段代码是我目前的进度,但是有问题:

#include <stdio.h>

#define printname(n) printf(#n);

#define GenerateShowValueFunc(type)\
type showValue_##type(type x)\
{\
printname(x);\
printf("=%d\n", x);\
return 0;\
}

GenerateShowValueFunc(double)
GenerateShowValueFunc(int)

int main()
{

double i = 5.2;
int j = 3;

showValue_double(i);
showValue_int(j);

}

我不知道如何让输出随类型而变化,也不知道如何显示变量的名称。 OA


这个原始任务描述:请引用下面的ShowValue.c:

#include <stdio.h>

GenerateShowValueFunc(double)
GenerateShowValueFunc(int)

int main()
{

double i = 5.2;
int j = 3;

showValue_double(i);
showValue_int(j);

}

通过[GenerateShowValueFunc(double)]和[GenerateShowValueFunc(int)]这两行宏调用,可以帮助我们生成为[showValue_double( double )]和[showValue_int( int )]函数,并在main()函数中叫。该程序的执行结果如下:

i=5.2000
j=3

请将定义GenerateShowValueFunc宏的代码插入到ShowValue.c程序中适当的位置,以便该程序能够顺利编译和运行。

最佳答案

一个快速而肮脏的解决方案是:

type showValue_##type(type x)\
{\
const char* double_fmt = "=%f\n";\
const char* int_fmt = "=%d\n";\
printname(x);\
printf(type##_fmt, x);\
return 0;\
}

编译器会优化掉没有使用的变量,因此不会影响性能。但它可能会产生警告“未使用变量”。您可以添加 null 语句,例如 (void)double_fmt; 来使其静音。


无论如何,这都是非常脆弱且容易出错的,从来不建议练习编写这样的宏。这不是您在现代 C 中进行泛型编程的方式。您可以通过向老师展示以下示例来教他们如何操作:

#include <stdio.h>

void double_show (double d)
{
printf("%f\n", d);
}

void int_show (int i)
{
printf("%d\n", i);
}

#define show(x) _Generic((x),\
double: double_show, \
int: int_show) (x) // the x here is the parameter passed to the function

int main()
{
double i = 5.2;
int j = 3;

show(i);
show(j);
}

这使用现代 C11/C17 标准 _Generic 关键字,它可以在编译时检查类型。该宏选择适当的函数来调用,并且它是类型安全的。调用者不需要担心调用哪个“show”函数,也不需要担心它们传递正确的类型。

关于c - 作业是关于使用宏的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67873060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com