[問題] 關於strchr

看板C_and_CPP作者 (特命係長摩野仁)時間11年前 (2012/10/24 09:29), 編輯推噓1(105)
留言6則, 4人參與, 最新討論串1/1
我不知道其它函式有沒有這個問題 不過我先描述一下 這是strchr的prototype char *strchr(const char *s,int c); 書本說明如下(C primer plus 5e): This function returns a pointer to the first location in the string s that holds the character c. The function returns the null pointer if the character is not found. 但是它在使用strchr的時候 卻是直接match char type的argument 我不打出全部程式了 我只打出用到的地方 { char ans; \\ans is not int type 無關緊要的句子...; ans = getchar(); while(strchr("abcde",ans)==NULL) \\argument is char type {無關緊要的句子...;} } 看完前後文跟範例之後 我覺得應該是書本的prototype有問題 就函式的說明跟使用 它的prototype應該如下 char *strchr(const char *s,char c); \\int c改成char c應該更嚴謹才對 後來我又到網路上搜索這個函式的資料 參考網址 http://www.cplusplus.com/reference/clibrary/cstring/strchr/ parameters在c的地方有這樣的解釋 character Character to be located. It is passed as its int promotion, but it is internally converted back to char for the comparison. 接下來就是我想問的問題 如果這樣宣告prototype的話 arguments didn't match parameters 這樣沒問題嗎 雖然知道它的動作模式 是把int當char看待 但是範例都直接丟char = = 而且會讓人搞混 (在看到範例之前 我以為這個c是用來計算字數的 Orz) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.41.119.4

10/24 11:51, , 1F
getchar回傳的是int喔,你的編譯器沒有警告嗎?
10/24 11:51, 1F

10/24 17:34, , 2F
It was declared as int for some historical reason
10/24 17:34, 2F

10/24 18:12, , 3F
getchar 需要 int 是因為可能回傳 EOF 之類的值
10/24 18:12, 3F

10/24 18:13, , 4F
strchr 就純粹是歷史包袱了
10/24 18:13, 4F

10/24 18:25, , 5F
嗯嗯 OK 謝謝 收到 感謝各位
10/24 18:25, 5F

10/24 22:00, , 6F
我以為都用int是要方便變數直接傳來傳去?
10/24 22:00, 6F
文章代碼(AID): #1GXqHT34 (C_and_CPP)