有关C和C++中的bool值的使用问题

今天写了一个C小程序,可是怎么编译都有错误,不论是在GCC中还是VC还是eclipse,都有莫民奇妙的错误,仔细看后才发现,原来我使用了bool值,而在C语言中根本就没有这个值,所以会出错,解决办法是加上有关bool的宏定义即可:

#include <stdio.h>
#include <stdlib.h>
#define BOOL int
#define TRUE 1
#define FALSE 0

struct array
{
	int count;
	int size;
	char *pBase;
};
void init_arr (struct array *pArr,int number);
void show_arr (const struct array *pArr);
BOOL is_empty (const struct array *pArr);

int main (void)
{
	struct array arr;

	init_arr (&arr,10);
	show_arr (&arr);

	return 0;	
}
void init_arr (struct array *pArr,int number)
{
	pArr->pBase = (char *)malloc(sizeof(char)*number);
	if (NULL == pArr->pBase)
	{
		printf ("Memory allocation failed!\a\n");
		exit(EXIT_FAILURE);
	}
	else
	{
		pArr->size = number;
		pArr->count = 0;
	}
	
	return;
}
void show_arr (const struct array *pArr)
{
	int i;
	if ( is_empty(pArr) )
		printf ("Array is empty!\a\n");
	else
	{
		for (i=0;i<(pArr->count);i++)
			printf ("%c ",pArr->pBase[i]);
		printf ("\n");
	}
	
	return;
}
BOOL is_empty (const struct array *pArr)
{
	if (pArr->count == 0)
		return TRUE;
	else
		return FALSE;
}

而此前的代码在C++中运行完好,这是因为C++中定义了bool值,故而可以使用:

#include <stdio.h>
#include <stdlib.h>

struct array
{
	int count;
	int size;
	char *pBase;
};
void init_arr (struct array *pArr,int number);
void show_arr (const struct array *pArr);
bool is_empty (const struct array *pArr);

int main (void)
{
	struct array arr;

	init_arr (&arr,10);
	show_arr (&arr);

	return 0;	
}
void init_arr (struct array *pArr,int number)
{
	pArr->pBase = (char *)malloc(sizeof(char)*number);
	if (NULL == pArr->pBase)
	{
		printf ("Memory allocation failed!\a\n");
		exit(EXIT_FAILURE);
	}
	else
	{
		pArr->size = number;
		pArr->count = 0;
	}
	
	return;
}
void show_arr (const  struct array *pArr)
{
	int i;
	if ( is_empty(pArr) )
		printf ("Array is empty!\a\n");
	else
	{
		for (i=0;i<(pArr->count);i++)
			printf ("%c ",pArr->pBase[i]);
		printf ("\n");
	}
	
	return;
}
bool is_empty (const struct array *pArr)
{
	if (pArr->count == 0)
		return true;
	else
		return false;
}

这是个简单的问题,不错如果不知道的话,还真是个苦恼的问题呢!!


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值