首頁 > 後端開發 > C++ > 主體

在C語言中,常數類型限定詞用來指定一個變數是一個常數,即其值在初始化後不能被修改。常數類型限定符可以透過將關鍵字const放在變數聲明前來實現。例如: const int x = 5; 在上述範例中,變數x被宣告為常數,其值被初始化為5,並且不能在後續的程式碼中被修改。常數類型限定符的使用可以提高程式碼的可讀性和可維護性,因為它明確地指示了變數的用途和限制

王林
發布: 2023-09-01 11:33:02
轉載
701 人瀏覽過

Type qualifiers add special attributes to existing datatypes in C programming language.

在C语言中,常量类型限定符用于指定一个变量是一个常量,即其值在初始化后不能被修改。常量类型限定符可以通过将关键字const放在变量声明前来实现。例如:

const int x = 5;
在上述示例中,变量x被声明为一个常量,其值被初始化为5,并且不能在后续的代码中被修改。常量类型限定符的使用可以提高代码的可读性和可维护性,因为它明确地指示了变量的用途和限制

There are three type qualifiers in C language and constant type qualifier is expf below −

Const

There are three types of constants, which are as follows −

  • Literal constants

  • #Defined constants

  • Memory constants

Literal constants − These are the unnamed constants that are used to specify data.

For example,

a=b+7 //Here ‘7’ is literal constant.
登入後複製

Defined constants − These constants use the preprocessor command 'define" with

##For example, #define PI 3.1415

Memory constants − These constants use 'C' qualifier 'const', which indicates that the data cannot be changed.

The syntax is as follows −

const type identifier = value
登入後複製

例如,

const float pi = 3.1415

如您所見,它只是給出一個字面名稱。

範例

#以下是常數型別限定符的C程式:

#include<stdio.h>
#define PI 3.1415
main ( ){
   const float cpi = 3.14
   printf ("literal constant = %f",3.14);
   printf ("defined constant = %f", PI);
   printf ("memory constant = %f",cpi);
}
登入後複製

輸出

當上述程式被執行時,它產生以下結果−

literal constant = 3.14
defined constant = 3.1415
memory constant = 3.14
登入後複製

以上是在C語言中,常數類型限定詞用來指定一個變數是一個常數,即其值在初始化後不能被修改。常數類型限定符可以透過將關鍵字const放在變數聲明前來實現。例如: const int x = 5; 在上述範例中,變數x被宣告為常數,其值被初始化為5,並且不能在後續的程式碼中被修改。常數類型限定符的使用可以提高程式碼的可讀性和可維護性,因為它明確地指示了變數的用途和限制的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!