Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ casting for different targets (compilers)

Given the following:

code-link

Here is the code itself for convenience (and I am not sure my link is working):

#include <iostream>
#include <vector>
#include <stdint.h>

using namespace std;

int main()
{
    cout<<"Hello World";
    std::vector<std::string> test_vect {"1", "2"};
    long unsigned int size = static_cast<long unsigned int>(test_vect.size());

    std::cout << "size: " << size << std::endl;
    return 0;
}

And the following compile options: g++ file.c -Wall -Wextra "-Werror" "-Wuseless-cast"

You can see here that I am casting vector.size() to long unsigned int, this gets flagged up as a useless cast on Wandbox (my link) however the same code running on my linux box does not give a warning - but it will give me a different warning if I dont cast it.

I understand that the two unsigned long vs size_t can be different. But what I am trying to do is write some code that has no warnings with all the casting warnings set (maybe this is optamisitic when cross compiling).

So, one compiler complains that I am converting types, so I cast, but then another compiler is complaining about useless cast - so I remove the cast - and around we go :(

Is there a good approach to this so that I dont get warnings on either compilers?

I was going to just remove the -Wuseless-cast option, but I thought I would see if anyone has other ideas...

like image 463
code_fodder Avatar asked Jan 01 '23 23:01

code_fodder


1 Answers

what I am trying to do is write some code that has no warnings with all the casting warnings set (maybe this is optamisitic when cross compiling)

It's optimistic when cross compiling if you have casts.

Is there a good approach to this so that I dont get warnings on either compilers?

Don't have casts. Make your variable be of type std::size_t.

I was going to just remove the -Wuseless-cast option

That's the other option.

like image 185
Lightness Races in Orbit Avatar answered Jan 13 '23 11:01

Lightness Races in Orbit