问题描述
我很抱歉我以前的帖子不完整。
这是正确的:
size_t len = strlen(myCString);
for(WHAT i = 0; i< len; ++ i)
{
//遍历字符串
//并做一些操作
}
在上面的代码中替换''WHAT'的最佳选择是什么?
size_t还是int?为什么?
I am sorry for my previous incomplete posting.
Here is the correct one:
size_t len = strlen( myCString ) ;
for( WHAT i = 0 ; i < len ; ++i )
{
// iterate through the string
// and do some operations
}
What is the best choice to replace ''WHAT'' in the above code?
size_t or int ? Why ?
推荐答案
如果你*知道*你的指数将*总是*落在''int''类型的范围内
,那么你可以使用它。
或者如果你不想被这些令人讨厌的
细节所困扰,可以在以后咬你,请使用''size_t ''
*保证*能够代表任何指数值。
所以既不是''int''也不是''size_t''必然是正确的或者
错误本身,但如果被问及建议,我说每当存储一个对象或一个数组索引的大小时,都要使用''size_t''
。
- Mike
If you *know* your indices will *always* fall in the range
of type ''int'', then you could use it.
Or if you don''t want to be bothered with such annoying
details that could bite you later, use ''size_t'' which
is *guaranteed* to be able to represent any index value.
So, neither ''int'' nor ''size_t'' is necessarily "right" or
"wrong" per se, but if asked for advice, I say use ''size_t''
whenever storing the size of an object or an array index.
-Mike
一个整数类型,不一定是int。
-
Al Balmer
Balmer Consulting
因为当前实现的C规范是这样说的。不要将C与C99或C ++混淆!
Because the currently implemented C specification says so. Do not
confuse C with C99 or C++ !
C99是C.值得指出的是C90仍然更为广泛
比C99实现,但这不会使C99无效或偏离主题。
我知道至少有两个C编译器(最近的gcc带有 - std = c99"和
英特尔的IA-64 ecc)声称支持C99并且似乎处理了(b i =
) 1; i< = 10; i ++)
构造正确。他们是否完全支持整个C99
语言是另一个问题。
-
Keith Thompson(The_Other_Keith)< http://www.ghoti.net/~kst>
圣地亚哥超级计算机中心< * GT; < http://www.sdsc.edu/~kst>
Schroedinger做莎士比亚:要*和*不要
C99 is C. It''s worth pointing out that C90 is still more widely
implemented than C99, but that doesn''t make C99 invalid or off-topic.
I know of at least two C compilers (a recent gcc with "-std=c99", and
Intel''s ecc for IA-64) that claim C99 support and seem to handle the
for (int i = 1; i <= 10; i ++)
construct correctly. Whether they fully support the entire C99
language is another question.
--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
这篇关于int或size_t作为字符串的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!