好习惯之函数先声明

经常看到一些多函数代码明明函数定义在主函数前面仍会先声明一遍函数
按照语法正确性来说 我们知道对于函数的声明与定义一般有两种情况:
1、函数在主函数前定义,此时可以直接声明并定义,即无需先声明函数头;
2、函数在主函数之后定义,在主函数前必须先声明函数;
故之前看到函数定义在前还声明函数的会觉得有点多此一举,今天自己在敲代码的时候才突然发现这样做的好处

#include <stdio.h>
#include <malloc.h>

typedef struct queue {
	int num;
	int data;
	struct queue *next;
}queue;

queue* initqueue(int size);
queue* gettail(queue *head, int *max);
int calculatetimes(queue *head, int m);
void freequeue(queue *head);

queue* initqueue(int size)
{
	int i;
	queue *head = (queue*)malloc(sizeof(queue));
	queue *tail = head;
	head->next = NULL;
	for (i = 1; i <= size; i++)
	{
		queue* node = (queue*)malloc(sizeof(queue));
		node->num = i;
		scanf("%d", &node->data);
		tail->next = node;
		node->next = NULL;
		tail = node;
	}
	return head;
}

int calculatetimes(queue* head, int m)
{
	int max, times = 0;
	queue *tail, *pre = head;
	head = head->next;
	tail = gettail(pre, &max);
	while (head)
	{
		if (head->data != max)
		{
			pre->next = head->next;
			tail->next = head;
			head->next = NULL;
			tail = head;
			head = pre->next;
		}
		else
		{
			++times;
			if (head->num == m)
				break;
			else
			{
				pre->next = head->next;
				free(head);
				head = pre->next;
				tail = gettail(pre, &max);
			}
		}
	}
	return times;
}

queue* gettail(queue *head, int *max)
{
	*max = 0;
	queue* tail = head;
	for (head = head->next; head; head = head->next)
	{
		tail = head;
		*max = *max > head->data ? *max : head->data;
	}
	return tail;
}

void freequeue(queue *head)
{
	queue *node = head;
	for (head = head->next; head; head = head->next)
	{
		free(node);
		node = head;
	}
}

int main(void)
{
	int n, m;
	queue *head;
	scanf("%d%d", &n, &m);
	head = initqueue(n);
	printf("%d", calculatetimes(head, m));
	freequeue(head);
	return 0;
}

多函数封装的时候常常会遇到函数嵌套的情况 经常会遇到函数先定义了然后run之后就报错有一些函数uninitialized
所以无论函数定义是否在main之前都先声明一遍函数名应该是一个不错的习惯
可以避免因函数嵌套引起的报错 也会形成更清晰的思路 在声明的时候就思考函数顺序如何摆放的问题
看似多此一举但是还是一个挺好的习惯的
以后写的时候可以多注意一下


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值