Re: [討論] 請板友幫忙review置底13誡--N.01

作者: tinlans ( )   2016-04-16 21:39:06
※ 引述《wtchen (沒有存在感的人)》之銘言:
: 應該修改的地方:
: - 如果變數不為以下屬性(預設為auto)或動態配置(malloc),
: 其初始值為undefined behavior:
indeterminate
: * static
: * _Thread_local
: * global variable (這個我在Standard沒找到)
6.7.9 Initialization
If an object that has automatic storage duration is not initialized explicitly,
its value is indeterminate. If an object that has static or thread storage
duration is not initialized explicitly, then:
...
- if it has arithmetic type, it is initialized to (positive or
unsigned) zero;
...
global variable 所擁有的是 static storage duration,所以初值會是正零或無號零。
但是因為國內很多人用 MCU,要小心有的編譯器會允許你甚至預設就違反這條規則。
: _Thread_local (C11新增?), and either with external or internal linkage
: (這啥?) or with the storage-class specifier static, has static storage
: duration. Its
上面 6.2.2 Linkages of identifiers 就在講 linkage 啊。
然後 paragraph 5:
If the declaration of an identifier for a function has no storage-class
specifier, its linkage is determined exactly as if it were declared with
the storage-class specifier extern. If the declaration of an identifier
for an object has file scope and no storage-class specifier, its linkage
is external.
什麼叫 an object has file scope and no storage-class specifier?
就是前面沒有標 extern 或 static 的 global variable,預設是 external linkage。
但是不管它是 static 還是 external linkage,它都擁有 static storage duration。
為什麼?因為上面你貼的那段就是這樣講了啊。
雖然規格書講得比較隱晦,但是其實用消去法也能發現該找哪邊才對。
翻一下規格書對 linkage 及 storage duration 的分類就會看到這兩句:
1. There are three kinds of linkage: external, internal, and none.
2. There are four storage durations: static, thread, automatic, and allocated.
global variable 這個英文片語在規格書裡沒被直接歸類,但必然還是在這遊戲規則裡。
你先把不可能的消去,然後去試圖證明它是你想像的那類,就能找出對應的文字敘述。
: lifetime is the entire execution of the program and its stored value is
: initialized only once, prior to program startup.
: static storage duration 包含:
: - _Thread_local (C11新增?)
: - 含有static 修飾字的變數
: 不過這邊似乎沒提到global variable也是被初始化為0....
因為 global variable 這個英文片語在標準規格書裡幾乎不使用。
: (這是我在Deep C的slide上看到的)
作者: wtchen (沒有存在感的人)   2016-04-16 21:41:00
感謝補充,最近才開始真正看standard,真的有好多眉角...所以indeterminate != undefined behavior?感謝說明,我想藉由這次13誡review的機會好好看一下standard,不管是新手還是老手都能受用。感謝,受教了,我還要再努力阿
作者: legendmtg (CLANNAD)   2016-04-16 23:26:00
大神出現了 <(_ _)>
作者: VictorTom (鬼翼&娃娃魚)   2016-04-18 01:25:00
有神快拜...<(_ _)>
作者: mabinogi805 (焚離)   2016-04-18 03:44:00
謝謝,受教了!<(_ _)>

Links booklink

Contact Us: admin [ a t ] ucptt.com