Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C 常量


常量

如果你不想让其他人(或你自己)更改现有的变量值,你可以使用 const 关键字。

这将声明变量为“常量”,这意味着它**不可更改**且**只读**

例子

const int myNum = 15;  // myNum 将始终为 15
myNum = 10;  // 错误:对只读变量 'myNum' 进行赋值
亲自尝试 »

当你拥有不太可能更改的值时,你应该始终将变量声明为常量

例子

const int minutesPerHour = 60;
const float PI = 3.14;
亲自尝试 »

关于常量的说明

当你声明一个常量变量时,它必须被赋予一个值

例子

像这样

const int minutesPerHour = 60;

然而,这**不会起作用**

const int minutesPerHour;
minutesPerHour = 60; // 错误
亲自尝试 »

良好实践

关于常量变量的另一件事是,将它们声明为大写被认为是良好的实践。

这不是必需的,但对于代码可读性很有用,并且是 C 程序员的常用做法

例子

const int BIRTHYEAR = 1980;
亲自尝试 »

C 练习

通过练习测试自己

练习

确保以下变量的值无法更改

 int hoursPerDay = 24;

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.