Reputation: 9432
Does a conversion like:
int a[3];
char i=1;
a[ static_cast<unsigned char>(i) ];
introduce any overhead like conversions or can the compiler optimize everything away?
I am interested because I want to get rid of -Wchar-subscripts
warnings, but want to use a char as index (other reasons)
Upvotes: 1
Views: 439
Reputation: 148890
I did one test on Clang 3.4.1 for this code :
int ival(signed char c) {
int a[] = {0,1,2,3,4,5,6,7,8,9};
unsigned char u = static_cast<unsigned char>(c);
return a[u];
}
Here is the relevant part or the assembly file generated with c++ -S -O3
_Z4ivala: # @_Z4ivala
# BB#0:
pushl %ebp
movl %esp, %ebp
movzbl 8(%ebp), %eax
movl .L_ZZ4ivalaE1a(,%eax,4), %eax
popl %ebp
ret
There is no trace of the conversion.
Upvotes: 3
Reputation: 136246
On most modern architectures char
and unsigned char
have the same size and alignment, hence unsigned char
can represent all non-negative values of char
and casting one to another does not require any CPU instructions.
Upvotes: 0