2016-01-19 78 views
-3

这里是我的代码在gcc c99,其中有我的代码中的“空值”?“无效值不被忽略,因为它应该是”当使用gcc

int main(int argc, char **argv) { 
    char *s = "smth"; 
    int r2 = ({ if (__builtin_types_compatible_p(__typeof__(s), char*)) { true; } else { false; }}); 
    return (0); 
}; 

更新

更糟的是,下面的代码有相同的错误

int main(int argc, char **argv) { 
    char *s = "smth"; 
    int r2 = ({if (1) {1;} else {0;}}); 
    return (0); 
}; 
+2

1)这是多么糟糕的原因。 2)你认为选择声明应该返回什么? - 无论如何,这不符合标准3)为什么不坚持标准并使用条件表达式 - 或者4)您根本不需要条件构造。 – Olaf

回答

2

你试图给if声明分配给int。该声明没有类型,因此您会看到错误。

你想,而不是什么ternary operator

condition ? true_value : false_valse 

如果condition计算结果为真,则表达式的true_value的值,否则它的false_value值。

所以,你要的是这样的:

int r2 = (__builtin_types_compatible_p(__typeof__(s), char*)) ? true : false; 

或者,由于这两个值只是truefalse

int r2 = __builtin_types_compatible_p(__typeof__(s), char*); 
1

声明

if (condition) {statement} 

将返回void和你不能用来初始化/分配一个变量。最好使用三元操作?:

int r2 = __builtin_types_compatible_p(__typeof__(s), char*) ? true : false 

或更好

bool r2 = __builtin_types_compatible_p(__typeof__(s), char*) // Use stdbool.h 

因为__builtin_types_compatible_p返回1如果给定类型相同,否则返回0

+2

1)当用布尔常量初始化时,为什么不使用'bool'? 2)为什么有条件的东西?只要'bool r2 = __builtin_types_compatible_p(__ typeof __(s),char *)'就足够清楚了(它应该有一个不言自明的名字)。 – Olaf

+0

@Olaf;实际上你是对的。我补充说。 – haccks

相关问题