我有这段代码,它可以很好地处理常规的有符号整数,我正在尝试编写一个与size_t工作的等效版本(因为现在开始和计数都是int,我需要它们是size_t):
int count,start;
for (start = (count-2)/2; start >=0; start--)
{
someFunction( x, start, count); // x is to illustrate function has other parameters
}我觉得这段代码对于一个非常简单的解决方案来说已经足够简单了,但我却一片空白。
发布于 2011-12-09 12:28:40
你可以像这样重写它:
start = count/2;
while (start > 0){
start--;
someFunction( x, start, count);
}否则,我能想到的唯一其他选择就是在已签名和未签名之间进行一些非标准兼容的转换……或者对~(size_t)0做些什么..。
以下是一些非标准兼容的替代方案:
for (start = (count-2)/2; (ssize_t)start >= 0; start--)
{
someFunction( x, start, count);
}
for (start = (count-2)/2; start != ~(size_t)0; start--)
{
someFunction( x, start, count);
}发布于 2011-12-09 18:33:55
size_t cnt, start;
for (start = cnt/2; start-- > 0; ) { ... }编辑如果OP真的想为cnt=1循环一次,那么三元是必要的:
for (start = (cnt==1) ? 1 : cnt/2; start-- > 0; ) { ... }发布于 2011-12-09 13:35:51
如果只使用一个减去一的值呢?
size_t start_plus_one;
for (start_plus_one = (count-2)/2+1; start_plus_one >=1; start_plus_one--)
{
someFunction( x, start_plus_one-1, count); // x is to illustrate function has other parameters
}https://stackoverflow.com/questions/8441054
复制相似问题