gcc extension中有case range的用法,如:
case 0x10 ... 0x1f:
這種用法在一些編譯器中無法支援,如MSVC。下面是一個自動將case range自動轉化為非case range且等價用法的指令碼。可以處理一行多個case的情況。
如有main.c:
#include <stdio.h>int main(){ int x; scanf("%d", &x); switch(x) { case 0x01: case 0x03 ... 0x10: printf("case 1\n"); break; case 0x1f ... 0x2f: printf("case 2\n"); break; default: printf("case 3\n"); break; } return 0;}
指令碼case_range_converter.py:
#!/usr/bin/pythonimport rewhile True: try: text = raw_input() except EOFError: break leading_space = "" result = re.findall(r"(\s*)case\s+0x([\da-f]+)(\s*\.\.\.\s*0x([\da-f]+))?", text) if result: for elem in result: if elem[0] and not leading_space: leading_space = elem[0] low_bound_str = elem[1] if elem[2]: high_bound_str = elem[3] else: high_bound_str = elem[1] low_bound = int(low_bound_str, 16) high_bound = int(high_bound_str, 16)# print low_bound# print high_bound for i in range(low_bound, high_bound + 1): print "%scase 0x%x:" % (leading_space, i) else: print text
運行:
./case_range_converter.py < main.c | tee main_no_case_range.c
得到main_no_case_range.c:
#include <stdio.h>int main(){ int x; scanf("%d", &x); switch(x) { case 0x1: case 0x3: case 0x4: case 0x5: case 0x6: case 0x7: case 0x8: case 0x9: case 0xa: case 0xb: case 0xc: case 0xd: case 0xe: case 0xf: case 0x10: printf("case 1\n"); break; case 0x1f: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: printf("case 2\n"); break; default: printf("case 3\n"); break; } return 0;}