【发布时间】:2019-07-25 18:32:55
【问题描述】:
我想在我的列表实现中支持负索引,我想要处理的方式(我知道可能有更好的方法来处理负索引)是通过将负值添加到列表中的元素总数。
因此,如果我的列表中有 12 个元素,并且我要求索引 -5,我会使用 12 + (-5) = 7,因此我用来检索元素的真实索引将是 7。
我认为一些类型转换是所有必要的,我可能可以尝试一堆类型,比如 ptrdiff_t 等——但我想学习如何确定要转换到的正确选择类型。
// the size of the list (normally something like list->num_nodes)
size_t list_size = 12;
// the int32_t is the index argument given to an indexing function
int32_t index = -5;
// the size_t is the real index that can be passed to my internal
// indexing function that will walk from either list head or tail
// depending on whether the index is closer to start or end.
size_t real_index = 0;
// if the index is less than 0 I want to add it to the list size
// to effectively subtract, otherwise just assign it
if (index < 0) {
real_index = (list_size + index); // << warning here
} else {
real_index = (size_t)index;
}
但是将 int32_t 索引添加到 size_t list_size 会导致 gcc 警告:
warning: conversion to ‘long unsigned int’ from ‘int32_t {aka int}’ may change the sign of the result [-Wsign-conversion]
解决将负 int32_t 添加到像 size_t 这样的无符号值的问题的正确方法是什么?我认为这是一个简单的答案,例如转换为同时处理 size_t 和 int32_t 的更大类型(int64_t?ptrdiff_t?)...但是您如何确定要转换为的正确类型(如果这是正确的解决方案)?
【问题讨论】:
-
奇怪,这没有给我任何警告 (
-Wall -Wextra -pedantic)。你用的是什么编译器? -
尝试 -Wconversion ./test.c:41:29:警告:从 'int32_t {aka int}' 转换为 'size_t {aka long unsigned int}' 可能会改变结果的符号 [ -Wsign-conversion] real_index = (list_size + index); //
标签: c unsigned signed integer-arithmetic