type casting in unavoidable circumstances

Hello,

I want to add a certain integer (say 10) at a certain index(say 5) of a vector. For this i am trying to make a following comparison in my code

1
2
3

if( (int)vector1.size() == index) 


So i need to make the data types on both side of the equation same. here i am converting size_t to int(which is the data type of 'index'). i know type conversions should be avoided but is the above code safe? Will it be better to convert int to size_t instead as 'size_t' will be always greater that 'int'? Please correct be if my assumption is wrong.

Regards
Saherch
i know type conversions should be avoided but is the above code safe?

No down casting can never be totally safe.

Will it be better to convert int to size_t instead as 'size_t' will be always greater that 'int'?

It would probably be better, but the best way would be to eliminate the cast all together. Instead of declaring index as an int declare it as a size_t.

Also if you must cast use C++ style casts, static_cast<>(), dynamic_cast<>(), etc.

Okay. Thank you for your response.
Topic archived. No new replies allowed.