Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++常量

作者:恋你如初   发布日期:2025-07-01   浏览:44

// C++ 常量示例代码

#include <iostream>
using namespace std;

int main() {
    // 1. 使用 const 关键字定义常量
    const int MAX_SIZE = 100;
    cout << "MAX_SIZE: " << MAX_SIZE << endl;

    // 2. 使用 #define 定义宏常量
    #define PI 3.14159
    cout << "PI: " << PI << endl;

    // 3. 使用 constexpr 定义编译时常量表达式
    constexpr int square(int x) {
        return x * x;
    }
    cout << "Square of 5: " << square(5) << endl;

    // 4. 字符串常量
    const char* greeting = "Hello, World!";
    cout << "Greeting: " << greeting << endl;

    return 0;
}

解释说明:

  1. const 关键字:用于定义常量,确保变量的值在程序运行期间不会被修改。例如 const int MAX_SIZE = 100;
  2. #define 预处理指令:用于定义宏常量,通常用于简单的替换操作。例如 #define PI 3.14159
  3. constexpr 关键字:用于定义编译时常量表达式,确保在编译时计算结果。例如 constexpr int square(int x)
  4. 字符串常量:使用 const char*std::string 来定义字符串常量,确保字符串内容不可变。例如 const char* greeting = "Hello, World!";

这些方法都可以用来定义常量,具体选择哪种方式取决于应用场景和需求。

上一篇:c++中const

下一篇:c++指针和引用的区别

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站