作者descent (「雄辯是銀,沉默是金」)
看板C_and_CPP
標題Re: [問題] 避免「變數名稱」衝突「class名稱」
時間Fri May 19 15:29:21 2017
我參考了 N1570
p35
An identifier can denote an object; a function; a tag or a member of a
structure, union, or
enumeration; a typedef name; a label name; a macro name; or a macro parameter.
p37
6.2.3 Name spaces of identifiers
1 If more than one declaration of a particular identifier is visible at any
point in a
translation unit, the syntactic context disambiguates uses that refer to
different entities.
Thus, there are separate name spaces for various categories of identifiers,
as follows:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by
following any32)
of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a
separate name
space for its members (disambiguated by the type of the expression used to
access the
member via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary
declarators or as
enumeration constants)
得到以下結論,
typedef int now_time; // typedef name
int now_time; // denote an object
當他們同時出現時, 處於同一個 name space,
所以無法區分他們的不同。
标准C语言指南 這本中文版書籍幫了很大的忙。
※ 引述《descent (「雄辯是銀,沉默是金」)》之銘言:
: 這個問題很詭異
: typedef int now_time;
: int main(int argc, char *argv[])
: {
: int now_time;
: now_time my_time;
: return 0;
: }
: descent@debian64:tmp$ gcc b.c
: b.c: In function 'main':
: b.c:6:12: error: expected ';' before 'my_time'
: now_time my_time;
: ^
: ---------------------------------------------------
: typedef int now_time;
: int main(int argc, char *argv[])
: {
: now_time my_time;
: int now_time;
: return 0;
: }
: 編譯正確
: 真奇怪!
--
紙上得來終覺淺,絕知此事要躬行。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.98.141.254
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1495178967.A.79C.html