设为首页 加入收藏

TOP

程序猿之---C语言细节26(C语言中布尔类型、continue细节、sizeof举例、strlen举例)
2015-01-22 20:49:34 来源: 作者: 【 】 浏览:14
Tags:程序 ---C 语言 细节 言中 布尔 类型 continue sizeof 举例 strlen

主要内容: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 
  
    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 
  
   

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 
  
    
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;
}
  
输出:

\

四、strlen举例

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       /* 问题 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; }
     
    
   
  
输出:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇有关c语言指针的总结 下一篇Objective-C基础笔记(8)Foundati..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: