C和C++ const用法的区别

C/C++ const用法的区别


区别一:const定义的常量:

const定义的常量:

    C语言:当修饰一个标识符的时候我们来说,这个标识符依然是一个变量,但是它具有常属性,不能被修改。即它定义的变量叫做常变量
     C++: const修饰的标识符就是一个常量

下面我们通过例子来解释一下它的区别:

eg1:
C语言和C++中,const修饰的标识符都不能直接被改变,下面的例子就是在不同的语言中出现的错误

C语言:

#include <stdio.h>
int main()
{
    int a = 10;
    const int b = 10;

    a = 20;//a是变量,a的值可以改变
    b = 20;
    printf("a = %d\n b = %d\n",a,b);
    return 0;
}

这里写图片描述

C++ :

#include <iostream>
using namespace std;
int main()
{
    int a = 10;
    const int b = 10;

    a = 20;//a是变量,a的值可以改变
    b = 20;
    cout<<"a = "<<a<<"\n"<<"b = "<<b;
    return 0;
}

这里写图片描述

eg2:

C语言中,const修饰的标识符是一个常变量,而非 常量
C++中,const修饰的标识符就是一个常量,而且必须初始化,一旦创建,其值就不可能改变。

C语言:

#include <stdio.h>
int main()
{
    const int b = 10;

    int arr [10];
    int arr1 [b];
    return 0;
}

这里写图片描述

C++ :

#include <iostream>
using namespace std;
int main()
{
    const int b = 10;

    int arr [10] = {0};
    int arr1 [b] = {0};
    return 0;
}

这里写图片描述

区别二: const定义函数


const定义函数
  C语言: 不可以定义const函数
   C++ : 可以定义const函数

猜你喜欢

转载自blog.csdn.net/qq_37941471/article/details/80678424