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

2014-11-23 18:02:59 · 作者: · 浏览: 7

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

#include 
#include 
#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 
#include 

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;
}