写一个简单的评估我遇到了一个有趣的问题。
给定代码:
enum node_type {LEAF, NODE};
struct tree_elm_t {
enum node_type type;
union {
struct tree_node_t node;
struct tree_leaf_t leaf;
} datum;
};
int parse_leaf(struct tree_leaf_t leaf);
int parse_node( struct tree_node_t node );
int parse_tree( struct tree_elm_t* tree );
....
int parse_tree( struct tree_elm_t* tree ) {
switch( tree->type ) {
case NODE: return parse_node(tree->datum.node);
case LEAF: return parse_leaf(tree->datum.leaf);
}
}
我很惊讶地看到 gcc 抱怨缺少控制流选项:
example.c: In function 'parse_tree':
example.c:54: warning: control reaches end of non-void function
流问题可以通过将返回值存储在一个变量中来解决,如下所示:
int parse_tree( struct tree_elm_t* tree ) {
int sum;
switch( tree->type ) {
case NODE: sum = parse_node(tree->datum.node); break;
case LEAF: sum = parse_leaf(tree->datum.leaf); break;
}
return sum;
}
然而,我确实发现原始代码更干净,有没有办法让 gcc 接受原始代码 - (我想进行静态分析以实现我的代码有效且干净)。
编辑:
我可能有点不清楚。
假设我编译了以下代码:
int parse_tree( struct tree_elm_t* tree ) {
int sum;
switch( tree->type ) {
case NODE: sum = parse_node(tree->datum.node); break;
// case LEAF: sum = parse_leaf(tree->datum.leaf); break;
}
return sum;
}
gcc 会给我一个警告:
example.c: In function 'parse_tree':
example.c:51: warning: enumeration value 'LEAF' not handled in switch
这意味着 gcc 对开关中的值选项有一定的了解,并且我已经注释掉了 LEAF 案例。这意味着 gcc 也知道在通过 switch 时正在检查每个案例。那么为什么声明:
control reaches end of non-void function
它是否缺少 gcc 中缺少的静态分析系统 - 或语言功能?