Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Implicit conversion of unsigned long long to signed long long?

Tags:

c++

I'm having a rather strange warning being reported by clang-tidy 12.0.1. In the following code:

#include <vector>

int main()
{
    std::vector<int> v1;

    const auto a = v1.begin() + v1.size();

    return 0;
}

I see this warning being triggered:

error: narrowing conversion from 'std::vector<int>::size_type' (aka 'unsigned long long') to signed type 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>::difference_type' (aka 'long long') is implementation-defined [bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions,-warnings-as-errors]
    const auto a = v1.begin() + v1.size();
                                ^

It was my understanding that when operating two integers with the same size but different signedness, the signed integer is converted to unsigned, not the other way around. Am I missing something here?

like image 201
Martin Avatar asked Sep 06 '25 02:09

Martin


1 Answers

Since C++20 a simple fix is to use std::sszie:

const auto a = v1.begin() + std::ssize(v1);
like image 123
bolov Avatar answered Sep 09 '25 04:09

bolov