C11 中 _Generic 的语法和示例用法

c++

1个回答

写回答

Face8080

2025-06-13 10:50

+ 关注

AI
AI

C11中引入了_Generic关键字,它是一个用于类型选择的泛型表达式。通过_Generic关键字,我们可以根据不同类型的参数选择不同的表达式来执行,从而实现更加灵活的编程。本文将介绍_Generic的语法和示例用法,并通过案例代码来说明其实际应用。

语法

_Generic关键字的语法如下所示:

_Generic(expression, type1: result1, type2: result2, ..., default: result)

其中,expression是我们要进行类型选择的表达式,type1、type2等是我们要判断的类型,result1、result2等是对应类型的结果,default是默认的结果。_Generic关键字会根据expression的类型选择相应的结果进行返回。

示例用法

下面通过几个示例来说明_Generic关键字的用法。

示例1:基本类型选择

假设我们要根据参数的类型选择不同的操作,比如对于整数类型,我们执行加法操作,对于浮点数类型,我们执行乘法操作,对于其他类型,我们执行默认的操作。代码如下所示:

c

#include <stdio.h>

#define operation(x) _Generic((x), \

int: x + 10, \

float: x * 2, \

default: x)

int mAIn() {

int a = 5;

float b = 3.5;

char c = 'A';

printf("operation(a) = %d\n", operation(a));

printf("operation(b) = %.2f\n", operation(b));

printf("operation(c) = %c\n", operation(c));

return 0;

}

输出结果为:

operation(a) = 15

operation(b) = 7.00

operation(c) = A

从输出结果可以看出,对于整数类型,_Generic选择执行了加法操作;对于浮点数类型,_Generic选择执行了乘法操作;对于字符类型,_Generic选择执行了默认的操作。

示例2:自定义类型选择

除了基本类型选择,我们还可以根据自定义的类型选择相应的操作。代码如下所示:

c

#include <stdio.h>

typedef struct {

int x;

int y;

} Point;

typedef struct {

float radius;

} Circle;

void draw_point(Point p) {

printf("Drawing a point at (%d, %d)\n", p.x, p.y);

}

void draw_circle(Circle c) {

printf("Drawing a circle with radius %.2f\n", c.radius);

}

#define draw_shape(shape) _Generic((shape), \

Point: draw_point, \

Circle: draw_circle, \

default: draw_default)(shape)

void draw_default() {

printf("Drawing a shape\n");

}

int mAIn() {

Point p = { 3, 4 };

Circle c = { 2.5 };

draw_shape(p);

draw_shape(c);

draw_shape(10);

return 0;

}

输出结果为:

Drawing a point at (3, 4)

Drawing a circle with radius 2.50

Drawing a shape

从输出结果可以看出,对于Point类型的参数,_Generic选择执行了draw_point函数;对于Circle类型的参数,_Generic选择执行了draw_circle函数;对于其他类型的参数,_Generic选择执行了默认的draw_default函数。

_Generic关键字是C11中引入的一个强大的泛型表达式,它可以根据不同类型的参数选择相应的操作。通过_Generic关键字,我们可以实现更加灵活和可读性高的代码。在实际应用中,我们可以根据具体的需求,利用_Generic关键字来处理不同类型的参数,提高代码的效率和可维护性。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号