前言
return,break,continue这三个都是控制语句,只是return 返回值可有可无,break,continue一般只是配合着循环语句使用,当然你要瞎几把用也行,只是表象会很奇怪,一般也不这用。
正文
- return : 表示终结返回一个值。
- break:表示跳出一个循环,不过没有循环时,就是返回一个null值
- continue:表示跳过当前循环,不过没有循环时,就是返回一个null值
return的实现
statement_control_t *execute_return_statement(return_statement_t *rs, hash_t *variable_table) {
statement_control_t *control_res = create_null_statement_control();
zvalue_t *expression_res = execute_expression(rs->expression, variable_table);
control_res->type = statement_control_type_return;
control_res->result = expression_res;
return control_res;
}
是不是很简单,就是运行返回的表达式的结果,结束
break的实现
statement_control_t *execute_break_statement() {
statement_control_t *control_res = create_null_statement_control();
control_res->type = statement_control_type_break;
return control_res;
}
更简单
continue的实现
statement_control_t *execute_continue_statement() {
statement_control_t *control_res = create_null_statement_control();
control_res->type = statement_control_type_continue;
return control_res;
}
也简单
控制语句的核心在
statement_control_t *execute_statement(statement_list_t *statement_list, hash_t *variable_table) {
// 空语句列表
if (is_empty(statement_list)) {
return create_default_statement_control();
}
int is_include = 0, is_break = 0;
statement_control_t *control_exe = NULL, *control_res = NULL;
statement_list_item_t *current, *old_top;
old_top = current = statement_list->top;
//
while (current) {
statement_t *statement = current->statement;
switch (statement->type) {
case statement_type_expression:
execute_expression_statement(statement->u.e, variable_table);
break;
case statement_type_return:
control_exe = execute_return_statement(statement->u.r, variable_table);
break;
case statement_type_if:
control_exe = execute_if_statement(statement->u.i, variable_table);
break;
case statement_type_continue:
control_exe = execute_continue_statement();
break;
case statement_type_global:
break;
case statement_type_for:
control_exe = execute_for_statement(statement->u.f, variable_table);
break;
case statement_type_break:
control_exe = execute_break_statement();
break;
case statement_type_include:
execute_include_statment(statement->u.in, statement_list);
is_include = 1;
break;
default:
error_exception("Undefined statement type(%d)!", statement->type);
}
// 判断运行的语句值并生成结果集
if (is_not_empty(control_exe)) {
switch (control_exe->type) {
case statement_control_type_return:
case statement_control_type_break:
case statement_control_type_continue:
control_res = control_exe;
is_break = 1;
break;
case statement_control_type_default:
default:
break;
}
}
if (is_break) {
break;
}
// 回到头部
if (is_include) {
current = statement_list->top;
is_include = 0;
} else {
current = current->next;
}
// 头部
statement_list->top = current;
}
statement_list->top = old_top;
//沒有运行值
if (is_empty(control_res)) {
control_res = create_default_statement_control();
}
return control_res;
}
结束语
return,break,continue 都是控制语句,特性不同,都会跳出当前的执行栈。跳出的动作不同。