C++入门(4):auto、范围for、nullptr

一、关键词 auto

1.1 概念

auto 作为一个新的类型指示符 来指示编译器,auto 声明的变量必须由编译器在编译时期推导而得。

cpp 复制代码
#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:

  1. 使用 auto 定义变量时,必须对其初始化。在编译阶段,编译器根据初始化表达式推导 auto 的实际类型。
  2. auto 并非一种类型声明,而是一种类型声明时的**"占位符"**,编译器在编译阶段会将 auto 替换为变量的实际类型。
1.2 使用
  1. 在声明指针时,auto 与 auto * 没有实际区别;在声明引用时,必须使用 auto&
cpp 复制代码
int main()
{ 	
    int a = 0;
    
    auto c = &a;
    auto* d = &a;
    auto& e = a;
    
    return 0;
}
  1. 同一行 定义多个变量时,变量类型必须相同,否则编译器会报错。
cpp 复制代码
int main()
{
    auto a = 10, b = 2.2;// error C3538: 在声明符列表中,"auto"必须始终推导为同一类型
    return 0;
}
  1. auto 不能用来声明数组
cpp 复制代码
int main()
{
    auto a[4] = {1, 2, 3, 4};// error C3318: "auto []": 数组不能具有其中包含"auto"的元素类型
    return 0;
}
  1. auto 不能用来做函数参数类型
cpp 复制代码
void f(auto) // error C3533: 参数不能为包含"auto"的类型
{
    // ...
}
int main()
{
    f(0);
    return 0;
}

二、基于范围的for循环

2.1
cpp 复制代码
#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结束整个循环。

2.2 范围for的使用条件
  1. for循环的迭代范围必须是确定的
cpp 复制代码
void Func(int arr[]) // error:arr数组的范围不确定
{
    for (auto e : arr)
        cout << e << " ";
}

三、指针空值nullptr

观察以下程序:

cpp 复制代码
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>文件中,可以看到:

cpp 复制代码
#ifndef NULL
    #ifdef __cplusplus
        #define NULL 0
    #else
        #define NULL ((void *)0)
    #endif
#endif

C++11 中引入新关键词 nullptr 表示指针空值,使用时不需要包含头文件。

sizeof(nullptr) 与 *sizeof((void)0)** 所占字节数相同,后续表示指针空值时最好使用 nullptr。

相关推荐
小灰灰搞电子37 分钟前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
神仙别闹1 小时前
基于 C++ 实现两个有序链表序列的交集
java·c++·链表
传奇开心果编程2 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
新时代牛马2 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
swordbob2 小时前
ReentrantLock 与 AQS 完整学习手册
java·开发语言
白山编程大哥3 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
hansang_IR3 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
落羽的落羽4 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
刚入门的大一新生4 小时前
Linux-进程控制
linux·运维·服务器·c++
shmily麻瓜小菜鸡4 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript