簡體   English   中英

如何正確地向size_t添加負數

[英]How to properly add a negative number to a size_t

我想支持我的列表實現上的負索引,我想要處理這種方式(我知道可能有更好的方法來處理負索引)是通過將負值轉換為它們的正當量,方法是將負值添加到總數中列表中的元素。

所以如果我的列表中有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?)的更大類型......但是如何確定要轉換為哪種類型(如果這是正確的解決方案)?

您可以將int32_tsize_t並添加它。 算術運算正常; 添加已轉換為無符號值的負值的結果將導致無符號值減去原始負值。

使用無符號數的算術以模M運算,其中M比最大可表示值多一個(例如,對於最大值為255的8位unsigned char ,為256)。 這包括轉化。 所以,如果我們有一個無符號有符號和負b,轉換b鍵無符號的類型的產率M + B(觀察到,由於B為負時, 為M + BM是以下)。 然后加入在數學上是一個 + M + B,其,模M,A + B。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM