This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/66170] Bogus warning with -Wsign-conversion when using static_cast<size_t> on an int
- From: "sir.vestnik at gmail dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Thu, 13 Oct 2016 14:23:51 +0000
- Subject: [Bug c++/66170] Bogus warning with -Wsign-conversion when using static_cast<size_t> on an int
- Auto-submitted: auto-generated
- References: <bug-66170-4@http.gcc.gnu.org/bugzilla/>
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66170
Sergey Vidyuk <sir.vestnik at gmail dot com> changed:
What |Removed |Added
----------------------------------------------------------------------------
CC| |sir.vestnik at gmail dot com
--- Comment #1 from Sergey Vidyuk <sir.vestnik at gmail dot com> ---
I have similair issue with gcc-6.2
[vestnik@VestniK-laptop C++]$ cat fasttest.cpp
#include <iostream>
#include <vector>
void foo(const std::vector<int> vec, const int idx) {
if (idx < 0 || vec.size() <= static_cast<size_t>(idx))
{
std::cout << "No such index\n";
return;
}
std::cout << "Valid index\n";
}
int main() {
foo({1, 2, 3, 4 ,5}, 6);
return 0;
}
[vestnik@VestniK-laptop C++]$ g++ -std=c++11 -Wsign-conversion -Wall -Werror
fasttest.cpp -o fasttest
fasttest.cpp: In function 'void foo(std::vector<int>, int)':
fasttest.cpp:5:31: error: conversion to 'std::vector<int>::size_type {aka long
unsigned int}' from 'const int' may change the sign of the result
[-Werror=sign-conversion]
if (idx < 0 || vec.size() <= static_cast<size_t>(idx))
^~~~~~~~~~~~~~~~~~~~~~~~
cc1plus: all warnings being treated as errors
[vestnik@VestniK-laptop C++]$ g++ --version
g++ (GCC) 6.2.1 20160830
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
It looks like static_cast type was incorrectly treated as const int instead of
size_t. Changing static_cast<size_t>(idx) to static_cast<unsigned>(idx)
silences diagnostics but such fix looks lihe a strange hack.