[問題] constant的定義

看板C_and_CPP作者 (brotherD)時間6年前 (2017/10/26 15:05), 6年前編輯推噓4(4016)
留言20則, 9人參與, 6年前最新討論串1/1
小弟最近在看很多sepc,注意到constant這個字好像跟我心目中的定義不太一樣。 我一直以為 3, 0x2A, 0b10001000這些就是所謂的constant 但看到這份文件: https://en.wikipedia.org/wiki/Constant_(computer_programming)#Comparison_with_literals_and_macros Definition: a constant is a value that cannot be altered by the program during normal execution 這段給我的感覺是,只要在normal exectuion的過程中,值不被改變就叫constant 問題一:什麼是normal execution? 接著文件又說: When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. 這段告訴我的意思是,以下程式碼: int a = 3; 只要a的值在normal execution過程中沒有被改變,那a就叫 named constant,並不叫 variable. 請問各位大大,我理解的方向是正確的嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.26.157 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1509001538.A.80F.html

10/26 15:16, 6年前 , 1F
是「不能」被改變
10/26 15:16, 1F
對欸,那我上面打錯了,應該是const int a = 3; ※ 編輯: zzss2003 (60.248.26.157), 10/26/2017 15:56:02

10/26 16:24, 6年前 , 2F
literal?
10/26 16:24, 2F

10/26 16:51, 6年前 , 3F
學而不做則罔。對就是不做。
10/26 16:51, 3F

10/26 17:43, 6年前 , 4F
3,0x2A係constant不錯呀,而int a = 3; 將3這個數值賦予給
10/26 17:43, 4F

10/26 17:46, 6年前 , 5F
**變數** a,a的初始值是3,不過是可以改變的
10/26 17:46, 5F

10/26 17:52, 6年前 , 6F
所以a依然係variable,至少編譯器不會阻止 a = 999;
10/26 17:52, 6F

10/26 18:34, 6年前 , 7F
看你在看什麼語言的spec, 一般人認為的constant可能
10/26 18:34, 7F

10/26 18:34, 6年前 , 8F
會跟spec定義的不太一樣
10/26 18:34, 8F

10/26 18:35, 6年前 , 9F
例如說在c spec裡面, const int a = 3;的 a 不是
10/26 18:35, 9F

10/26 18:35, 6年前 , 10F
constant
10/26 18:35, 10F

10/26 18:38, 6年前 , 11F
寫 enum {X = a}, compiler會對這個a有意見
10/26 18:38, 11F

10/26 18:39, 6年前 , 12F
但是在一般人的定義裡面a是個constant
10/26 18:39, 12F

10/26 19:19, 6年前 , 13F
我是當作int,有const的特性@@
10/26 19:19, 13F

10/27 00:16, 6年前 , 14F
你把一個int vale丟到 func(const int &val,...)
10/27 00:16, 14F

10/27 00:17, 6年前 , 15F
你可以很確認的知道value不會被改變
10/27 00:17, 15F

10/27 00:17, 6年前 , 16F
或是你從 const data_t func(...)獲得資料
10/27 00:17, 16F

10/27 00:18, 6年前 , 17F
你可以知道你獲的的data是無法改變的
10/27 00:18, 17F

10/27 00:18, 6年前 , 18F
但是可以 看 or copy
10/27 00:18, 18F

10/27 00:51, 6年前 , 19F
樓上return const value是沒有意義的
10/27 00:51, 19F

10/27 01:07, 6年前 , 20F
先看看C規格書怎麼寫
10/27 01:07, 20F
文章代碼(AID): #1PyOb2WF (C_and_CPP)