码迷,mamicode.com
首页 > 编程语言 > 详细

程序猿之---C语言细节26(C语言中布尔类型、continue细节、sizeof举例、strlen举例)

时间:2014-11-23 17:36:30      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:c语言细节   面试   strlen   sizeof   

主要内容:C语言中布尔类型、continue细节、sizeof举例、strlen举例

一、布尔类型

可能很多人不知道现在C语言已经有了布尔类型:从C99标准开始,类型名字为"_Bool"

在C99标准之前我们常常自己模仿定义布尔类型,常见有以下几种方式:

1、方式一

#define TURE 1
#define FALSE 0

2、方式二

typedef enum {false, true} bool;

3、方式三

typedef int bool

闲int浪费内存,对内存敏感的程序使用

typedef char bool

C99标准中新增的头文件中引入了bool类型,与C++中的bool兼容。该头文件为stdbool.h,其源码如下所示:

#ifndef _STDBOOL_H 
#define _STDBOOL_H 
 
#ifndef __cplusplus 
 
#define bool    _Bool 
#define true    1 
#define false   0 
 
#else /* __cplusplus */ 
 
/* Supporting <stdbool.h> in C++ is a GCC extension.  */ 
#define _Bool   bool 
#define bool    bool 
#define false   false 
#define true    true 
 
#endif /* __cplusplus */ 
 
/* Signal that all the definitions are present.  */ 
#define __bool_true_false_are_defined 1#endif /* stdbool.h */ 

二、continue

continue细节就是要在循环中使用,不然会报错

#include <stdio.h>

int main()
{
	int a = 1;
	switch(a)
	{
		case 1:
			printf("1\n");
	 		continue; // continue必须用在循环中 
	 		break;
		case 2:
			printf("2\n");
		default:
			break;
	}
	return 0;
}

三、sizeof举例

#include <stdio.h> 
int b[100];
void fun(int b[100])
{
	printf("in fun sizeof(b) = %d\n",sizeof(b)); //感觉函数中数组按指针处理的 
}
int main()
{
	char *p = NULL;
	printf("sizeof(p) = %d\n",sizeof(p));
	printf("sizeof(*p) = %d\n",sizeof(*p));
	
	printf("-----------------------\n");
	char a[100];
	printf("sizeof(a) = %d\n",sizeof(a));
	printf("sizeof(a[100]) = %d\n",sizeof(a[100]));
	printf("sizeof(&a) = %d\n",sizeof(&a));
	printf("sizeof(&a[0]) = %d\n",sizeof(&a[0]));
	printf("-----------------------\n");
	fun(b);
	return 0;
}
输出:

bubuko.com,布布扣

四、strlen举例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
/*
	问题 
	1、-0和+0在内存中分别怎么存储
	2、int i = -20;
	   unsigned j = 10;
	   i+j的值为多少?为什么? 
	3、 下面代码有什么问题?
	unsigned i;
	for(i = 9; i>=0; i--) 
	{
		printf("%u\n",i);
	}
*/
int main()
{
	bool bool2 = 0;  /* C语言bool类型是在C99才有的,如果没有包含头文件stdbool.h,直接用bool会报错误*/ 
	_Bool bool1 = 1; /*直接使用_Bool不用包含stdbool.h*/
	char a[280];
	char *str = "12340987\0 56";
	char test[] = "12340987 56";
	int i;
	printf("strlen(a) = %d\n",strlen(a));
	for(i = 0; i < 280; i++)
	{
		a[i] = -1-i; // a[256]  = 0
	//	printf("a[%d] = %d\n",i,a[i]);
	}

	printf("strlen(a) = %d\n",strlen(a));  // 为什么是255 
	printf("strlen(str) = %d\n",strlen(str));
	printf("strlen(test) = %d\n",strlen(test));
	
	char s = '\0';
	printf("\\0 = %d\n",s);	
	return 0;
}
输出:

bubuko.com,布布扣

程序猿之---C语言细节26(C语言中布尔类型、continue细节、sizeof举例、strlen举例)

标签:c语言细节   面试   strlen   sizeof   

原文地址:http://blog.csdn.net/human_evolution/article/details/41412249

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!