C 入门4auto范围fornullptr
墨初 知识笔记 91阅读
一、关键词 auto 1.1 概念
使用 auto 定义变量时必须对其初始化。在编译阶段编译器根据初始化表达式推导 auto 的实际类型。auto 并非一种类型声明而是一种类型声明时的**”占位符“**编译器在编译阶段会将 auto 替换为变量的实际类型。 1.2 使用 在声明指针时auto 与 auto* 没有实际区别在声明引用时必须使用 auto&。
2.2 范围for的使用条件 for循环的迭代范围必须是确定的
auto 作为一个新的类型指示符来指示编译器auto 声明的变量必须由编译器在编译时期推导而得。
#include <iostream>using namespace std;int main(){ int a 0; auto b a; auto c &a; auto* d &a; auto& e a; cout << typeid(b).name() << endl; cout << typeid(c).name() << endl; cout << typeid(d).name() << endl; cout << typeid(e).name() << endl; return 0;}
PS:

int main(){ int a 0; auto c &a; auto* d &a; auto& e a; return 0;}
在同一行定义多个变量时变量类型必须相同否则编译器会报错。 int main(){ auto a 10, b 2.2;// error C3538: 在声明符列表中“auto”必须始终推导为同一类型 return 0;}
auto 不能用来声明数组。 int main(){ auto a[4] {1, 2, 3, 4};// error C3318: “auto []”: 数组不能具有其中包含“auto”的元素类型 return 0;}
auto 不能用来做函数参数类型。 void f(auto) // error C3533: 参数不能为包含“auto”的类型{ // ...}int main(){ f(0); return 0;}
二、基于范围的for循环 2.1 #include <iostream>using namespace std;int main(){int array[] { 1, 2, 3, 4, 5 };for (auto e : array)cout << e << ;return 0;}
PS:
与普通for循环相同可以使用continue结束本次循环使用break结束整个循环。

void Func(int arr[]) // errorarr数组的范围不确定{ for (auto e : arr) cout << e << ;}
三、指针空值nullptr 观察以下程序
void f(int){ cout << f(int) << endl;}void f(int*){ cout << f(int*) << endl;}int main(){ f(0); f(NULL); return 0;}
NULL
实际是个宏在<corecrt.h>
文件中可以看到
#ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif#endif
在C11中引入新关键词 nullptr 表示指针空值使用时不需要包含头文件。
sizeof(nullptr) 与 sizeof((void)0)* 所占字节数相同后续表示指针空值时最好使用 nullptr。
标签: