如果我不希望调用 strcmp 所需的开销,我将按照以下代码示例中描述的方式将字符串与短字符串文字进行比较:
#ifdef LITTLE_ENDIAN //little-endian-addressing
#define BytesAsDWord_M(a, b, c, d)\
((ulong) ((a) | ((b) << 8) | ((ulong) (c) << 16) | ((ulong) (d) << 24)))
#define BytesAsWord_M(a, b)((ushort) ((a) | ((b) << 8)))
#else //LITTLE_ENDIAN //little-endian-addressing
#define BytesAsDWord_M(a, b, c, d)\
((ulong) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24)))
#define BytesAsWord_M(a, b) ((ushort) ((b) | ((a) << 8)))
#endif //LITTLE_ENDIAN //little-endian-addressing
bool AbsCompare(char* chr_p)
//compare string with "abs"
{
if (*((ulong*) &chr_p[1]) ==
BytesAsDWord_M('a', 'b', 's', '\0'))
return true;
return false;
}
只要我在未启用优化选项的情况下进行编译,gcc 就会编译此示例。启用优化后,我收到警告:
“取消引用类型双关指针将破坏严格的别名规则”
如示例所示,即使使用 -O3 进行优化也不会产生有效的代码:
//abstest.c
#include <string.h>
typedef unsigned long ulong;
typedef unsigned short ushort;
#if BYTE_ORDER == LITTLE_ENDIAN //little-endian-addressing
#define BytesAsDWord_M(a, b, c, d)\
((ulong) ((a) | ((b) << 8) | ((ulong) (c) << 16) | ((ulong) (d) << 24)))
#define BytesAsWord_M(a, b)((ushort) ((a) | ((b) << 8)))
#else //BYTE_ORDER == LITTLE_ENDIAN //little-endian-addressing
#define BytesAsDWord_M(a, b, c, d)\
((ulong) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24)))
#define BytesAsWord_M(a, b) ((ushort) ((b) | ((a) << 8)))
#endif //BYTE_ORDER == LITTLE_ENDIAN //little-endian-addressing
int AbsCompare1(char* chr_p)
{
return *(ulong*) chr_p == BytesAsDWord_M('a', 'b', 's', '\0');
}
int AbsCompare2(char* chr_p)
{
return strcmp(chr_p, "abs");
}
int main(int argc __attribute__((unused)), char ** argv)
{
int i;
int j;
i = AbsCompare1(argv[0]);
j = AbsCompare2(argv[0]);
return i + j;
}
objdump -d -Mintel 绝对测试:
080483d0 <AbsCompare1>:
80483d0: 55 push ebp
80483d1: 89 e5 mov ebp,esp
80483d3: 8b 45 08 mov eax,DWORD PTR [ebp+0x8]
80483d6: 5d pop ebp
80483d7: 81 38 61 62 73 00 cmp DWORD PTR [eax],0x736261
80483dd: 0f 94 c0 sete al
80483e0: 0f b6 c0 movzx eax,al
80483e3: c3 ret
080483f0 <AbsCompare2>:
80483f0: 55 push ebp
80483f1: 0f b6 0d 5c 85 04 08 movzx ecx,BYTE PTR ds:0x804855c
80483f8: 89 e5 mov ebp,esp
80483fa: 8b 55 08 mov edx,DWORD PTR [ebp+0x8]
80483fd: 0f b6 02 movzx eax,BYTE PTR [edx]
8048400: 29 c8 sub eax,ecx
8048402: 75 2b jne 804842f <AbsCompare2+0x3f>
8048404: 0f b6 42 01 movzx eax,BYTE PTR [edx+0x1]
8048408: 0f b6 0d 5d 85 04 08 movzx ecx,BYTE PTR ds:0x804855d
804840f: 29 c8 sub eax,ecx
8048411: 75 1c jne 804842f <AbsCompare2+0x3f>
8048413: 0f b6 42 02 movzx eax,BYTE PTR [edx+0x2]
8048417: 0f b6 0d 5e 85 04 08 movzx ecx,BYTE PTR ds:0x804855e
804841e: 29 c8 sub eax,ecx
8048420: 75 0d jne 804842f <AbsCompare2+0x3f>
8048422: 0f b6 42 03 movzx eax,BYTE PTR [edx+0x3]
8048426: 0f b6 15 5f 85 04 08 movzx edx,BYTE PTR ds:0x804855f
804842d: 29 d0 sub eax,edx
804842f: 5d pop ebp
8048430: c3 ret
是否有可能直接比较这个简短的文字而无需将 chr_p 嵌入到联合中,特别是因为我想在“&chr_p[1]”之类的任意索引处比较 chr_p?