从C到C++快速入门(1. C标准库 -- 注释 -- 条件编译 )

C标准库的C++移植

  • C++中包含了C标准库的移植版本,C标准库的头文件x.h基本上变成了cx。如stdio.h在C++中对应的时cstdio、math.h变成了cmath、string.h变成了cstring
  • 但也有例外,比如 malloc.h 仍然没变

注释

多行注释 :(块注释)
/* … */
单行注释
//

示例代码
#define _CRT_SECURE_NO_WARNINGS //表示不提出警告
#include // 标准输入输出函数
#include
#include // 字符串处理函数
/*
int main(){
printf(“hello world !!\n”);
double x = 3.14;
printf("%lf , %lf\n", sqrt(x), sin(x));

char s1[10] = “hello”; // 因为包含结尾的接受字符: \0 所以一 共 6个字符
puts(s1);
// char s2[6]; // 这里如果小于6,则会因为空间太小而出现终止,所以这里填6
char s2[20];
strcpy(s2, s1); // 将s1拷贝给s2
puts(s2);
strcpy(s2, “world”);
puts(s2);
strcat(s2, “123456zqw”); //将字符串内容 拼接 到之前s2内容
// 注意: 这里s2空间范围要增大
puts(s2);
printf(“strlen(s1):%d, strlen(s2):%d\n”, strlen(s1), strlen(s2) );
return 0;
}
*/
int main(){

}

条件编译

表示预处理器遇到这些代码,会将它全部删除
#if 0

#endif


表示有效代码
#if 1

#else

#endif


#if 1

#elif

#elif

#endif


xxx : 宏

#ifdef xxx

#endif


#ifndef xxx

#else

#endif


示例代码:

  1. 功能: 将if 0 代码忽略, 只执行 if 1代码块
    打印出:hello if 1 !!

#if 0
#define _CRT_SECURE_NO_WARNINGS //表示不提出警告
#include // 标准输入输出函数
#include
#include // 字符串处理函数
int main(){
printf(“hello if 0 !!\n”);
}
#endif
#if 1
#define _CRT_SECURE_NO_WARNINGS //表示不提出警告
#include // 标准输入输出函数
#include
#include // 字符串处理函数
int main(){
printf(“hello if 1 !!\n”);
}
#endif


功能: 输出 hello world

#if 1
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include <malloc.h>
int main() {
#if 0
char s1[10];
strcpy(s1, “hello”);
puts(s1);
#else
char *s1 = (char *)malloc(12 * sizeof(char)); //分配12个char类型的空间
strcpy(s1, “hello world”);
puts(s1);
#endif
}
#endif

如果把if 0 改为 if 1
则上面代码有效, 打印出 hello

发布了41 篇原创文章 · 获赞 1 · 访问量 498

猜你喜欢

转载自blog.csdn.net/weixin_44773006/article/details/103303273