c++ - 如果使用无符号整数,通过减去 1 将基于 1 的编号转换为基于 0 的编号是否安全?

标签 c++ c

在我维护的系统中,用户从基于 1 的索引方案的集合中请求元素。在 C++/C 中,值存储在从 0 开始的数组中。

如果错误输入 0 作为此函数的输入,以下假设代码是否可移植?将基于 1 的编号方案转换为基于 0 的编号方案时,是否有更好的方法来验证用户的输入?

const unsigned int arraySize;
SomeType array[arraySize];    

SomeType GetFromArray( unsigned int oneBasedIndex )
{
  unsigned int zeroBasedIndex = oneBasedIndex - 1;

  //Intent is to check for a valid index.
  if( zeroBasedIndex < arraySize )
  {
    return array[zeroBasedIndex];
  }

  //else... handle the error
}

我的假设是 (unsigned int)( 0 - 1 ) 总是大于 arraySize;这是真的吗?

正如一些人在下面的回答中所建议的那样,另一种方法是检查 oneBasedIndex 并确保它大于 0:

const unsigned int arraySize;
SomeType array[arraySize];    

SomeType GetFromArray( unsigned int oneBasedIndex )
{
  if( oneBasedIndex > 0 && oneBasedIndex <= arraySize )
  {
    return array[oneBasedIndex - 1];
  }

  //else... handle the error
}

最佳答案

对于无符号类型,0-1 是该类型的最大值,因此它始终是 >= arraySize。换句话说,是的,那是绝对安全的。

关于c++ - 如果使用无符号整数,通过减去 1 将基于 1 的编号转换为基于 0 的编号是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9897698/

相关文章:

C 预处理器将 "int x"拆分为 int & x

c++ - 使用立方体贴图(不是反射贴图)对球体进行纹理化

c++ - 比较 C 中 char[] 的相等性

c++ - 创建新的 visual studio 项目,添加文件并运行它 - 命令行

c++ - 简单的自动换行功能最后一行问题

c - 使用数组的堆栈实现

C - 无法使用指针执行函数

c - 如何在不使用 C 中的 malloc 的情况下跟踪和排序指针?

c++ - 从非托管 C++ 调用 PowerShell 脚本

c++ - 奇怪的代码错误