转换为static_cast <unsigned char =“”>

时间:2015-06-19 08:47:37

标签: c++ c++11

转换如下:

int a[3];
char i=1;
a[ static_cast<unsigned char>(i) ];

引入任何开销,如转换,还是编译器可以优化所有内容? 我感兴趣因为我想摆脱-Wchar-subscripts警告,但想使用char作为索引(其他原因)

2 个答案:

答案 0 :(得分:3)

我在这段代码上对Clang 3.4.1进行了一次测试:

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];
}

以下是使用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

没有转换痕迹。

答案 1 :(得分:0)

在大多数现代体系结构unsigned charunsigned char具有相同的大小和对齐方式,因此char可以表示input <- data.frame(label = c("red", "red", "blue", "green", "green", "green", "orange"), count = c(2, 2, 1, 3, 3 ,3, 1)) 的所有非负值并且相互拼接不需要任何CPU指令。