复合字面量和结构(C99)

作者:追风剑情 发布于:2020-3-10 16:27 分类:C

示例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>

#define MAXTITL 41
#define MAXAUTL 31

struct book {
	char title[MAXTITL];
	char author[MAXAUTL];
	float value;
};

struct rect { double x; double y; };

double rect_area(struct rect r);
double rect_areap(struct rect * rp);

int main(int argc, char* argv[])
{
	struct book readfirst;
	int score;

	printf("Enter test score\n");
	scanf("%d", &score);

	if (score >= 84)
		//用复合字面量为结构赋值
		readfirst = (struct book){ "Crime and Punishment",
								"Fyodor Dostoyevsky",
								11.25 };
	else
		//用复合字面量为结构赋值
		readfirst = (struct book){ "Mr. Bouncy's Nice Hat",
								"Fred Winsome",
								5.99};

	printf("Your assigned reading:\n");
	printf("%s by %s: $%.2f\n", readfirst.title,
		readfirst.author, readfirst.value);

	//将复合字面量作为函数参数传递
	double area;
	area = rect_area((struct rect) {10.5, 20.0});

	double area1;
	area1 = rect_areap(&(struct rect) {10.5, 20.0});
	printf("area=%.2f, area1=%.2f\n", area, area1);

	/*
	C99的复合字面量特性可用于结构和数组。如果只需要一个临时结构值,
	复合字面量很好用。例如,可以使用复合字面量创建一个数组作为函数的参数
	或赋给另一个结构。语法是把类型名放在圆括号中,后面紧跟一个用花括号括起来的
	初始化列表。

	复合字面量在所有函数的外部,具有静态存储期;如果复合字面量在块中,
	则具有自动存储期。复合字面量和普通初始化列表的语法规则相同。这意味着,
	可以在复合字面量中使用指定初始化器。
	*/

	system("pause");
	return 0;
}

double rect_area(struct rect r) 
{
	return r.x * r.y;
}

double rect_areap(struct rect* rp)
{
	return rp->x * rp->y;
}

运行测试

11.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号