请根据C11标准的文法集推导代码 int main() { printf("Hello world!\n"); return 0; }
时间: 2024-05-24 22:11:37 浏览: 61
单片机"Hello world!"
程序的起始符号为translation_unit,它由external_declaration组成。
external_declaration可以是function_definition,也可以是declaration。
因为我们的程序包含一个函数定义,所以我们可以推导出以下文法:
translation_unit -> external_declaration
external_declaration -> function_definition
function_definition -> declaration_specifiers declarator compound_statement
declaration_specifiers -> ε
declarator -> direct_declarator
direct_declarator -> identifier ( )
compound_statement -> { statement_list }
statement_list -> statement
statement -> expression_statement
expression_statement -> expression ;
expression -> assignment_expression
assignment_expression -> conditional_expression
conditional_expression -> logical_or_expression
logical_or_expression -> logical_and_expression
logical_and_expression -> inclusive_or_expression
inclusive_or_expression -> exclusive_or_expression
exclusive_or_expression -> and_expression
and_expression -> equality_expression
equality_expression -> relational_expression
relational_expression -> shift_expression
shift_expression -> additive_expression
additive_expression -> multiplicative_expression
multiplicative_expression -> cast_expression
cast_expression -> unary_expression
unary_expression -> postfix_expression
postfix_expression -> primary_expression
primary_expression -> identifier
根据以上文法,我们可以推导出以下代码:
int main() { printf("Hello world!\n"); return 0; }
可以被表示为以下语法树:
translation_unit
|
external_declaration
|
function_definition
| |
| declarator
| |
declaration_specifiers ε
|
compound_statement
|
statement_list
|
statement
|
expression_statement
|
expression
|
assignment_expression
|
conditional_expression
|
logical_or_expression
|
logical_and_expression
|
inclusive_or_expression
|
exclusive_or_expression
|
and_expression
|
equality_expression
|
relational_expression
|
shift_expression
|
additive_expression
|
multiplicative_expression
|
cast_expression
|
unary_expression
|
postfix_expression
|
primary_expression
|
identifier "printf"
|
string_literal "Hello world!\n"
阅读全文