C语言基础(下)

1.结构类型

#include <stdio.h>

struct date {
    
    
	int year;
	int month;
	int day;
};

int main() {
    
    
	struct date today = {
    
    2021, 03, 17};
	struct date tomorrow = today;
	tomorrow.day = 18;

	printf("Today is %i-%i-%i\n", today.year, today.month, today.day);
	printf("Tomorrow is %i-%i-%i\n", tomorrow.year, tomorrow.month, tomorrow.day);
	return 0;
}

输出:

Today is 2021-3-17
Tomorrow is 2021-3-18

知识点:1.结构不同于数组,其内容可以改动,比如tomorrow.day = 18,而数组内容是不可改动的

结构函数
之前提到函数返回值是一个数,因此需要返回多个值时候我们会使用指针。我们把上面的例子改一改

2.自定义数据类型

//case 1
typedef int new_int;
//case 2
typedef struct Adate{
    
    
	int month;
	int day;
	int year;
} Date;
//case 3
typedef struct {
    
    
	int month;
	int day;
	int year;
} Date;


知识点:typedef给已有的数据类型声明新名字。
比如case 1,在后续程序里,可以用new_int去定义整型变量。
case 2是给struct Adate类型起别名,之后可以用Date直接定义这种类型。(注意,struct Adate才是类型,单独的Adate不是,所以typedef的使用简化了类型名称)
case 3则直接给类型起名叫Date

3.宏定义

什么是宏?就是文字替换

#define PI 3.14159

#开头的是编译预处理指令,#define用来定义宏,PI是宏的名字,3.14159是宏的值
当然,也有预定义的宏,如下所示

#include <stdio.h>

int main() {
    
    

	printf("%s\n", __FILE__);
	printf("%d\n", __LINE__);
	printf("%s\n", __DATE__);
	printf("%s\n", __TIME__);
	return 0;
}

输出结果

E:\dustbin\array.c
7
Mar 17 2021
20:40:54

也可以像函数一样定义宏

#include <stdio.h>

#define cube(x) ((x)*(x)*(x))
int main() {
    
    

	printf("%d\n", cube(5));

	return 0;
}

cube(5)会被5 * 5 * 5替换,注意到这里替换是文字替换,所以要考虑替换后运算优先级,最好给x加括号,不要写成(x * x * x)

猜你喜欢

转载自blog.csdn.net/weixin_44823313/article/details/114940509