Identity expression, factor, and term?

我只是一个虾纸丫 提交于 2019-12-07 09:51:48

问题


I am learning context-free grammar, and I don't understand how to identity expression, factor and term in a programming language like C or C++.

Suppose we have an assignment statement, id := E, where E is any arithmetic expression.

What is a term? What is an expression? and What is a factor in an actual piece of code?

We can have

int i = 3, j = 14
int i = 3 + j * 14;

Thank you very much.


回答1:


The "factor", "term" and "expression" concepts come from math and don't really have to do with programming languages.

Factors are things you multiply:

1*2*(3+4)

Terms are things you add:

1 + 2 + (3*4)

And expressions are for the whole result

1 + 3 * 7

In context-free language parsing you use these distinctions to organize the precedences between operators. So an expression is made of a sum of terms and a term is made of a product of factors and a factor is either a number or a parenthesized subexpression.




回答2:


Your homework probably also has a grammar specification for a (subset of a) programming language like C or C++ , something along the lines of:

Program->Expression|Definition|Declaration
Expression->Expression + Term
Expression->Expression - Term
Expression->Expression*Factor
...
...
...
etc etc.

Then, 3 + j*14 is an expression, 3 is a term (anything connected by a + is either an Expression or a Term according to the grammar above) j and 14 are factors Please note that a grammar above is a very crude imitation of what a grammar of a real programming language might look like.




回答3:


Ok so suppose we have a grammar like this:

Program->(Definitions | lambda)
Definitions->Definitions Definitions

Definitions-> "int" Definition ";" |"int" Definition,Definition ";"
Definition -> Name "=" Expression

Expression-> Term "+" Expression
Expression->Expression "-" Term
Expression->Expression "*" Factor
Term->"3"|"14"
Factor->"3"|"14"
Expression->"3"|"14"

Note that my terminal symbols are in quotes and I omit the part where Name is defined as a combination of letters and numbers and underscores starting with a letter or an underscore :)

So, in your example:

Line 1 int i = 3, j = 14;
Line 2 int i = 3 + j * 14;

i and j are Names. 3, 14 (line 1) and 3 + j*14 (line 2) are are Expressions. Then,on line 2, 3 is a Term, j*14 is an Expression, j is a Factor and 14 is a Factor :)



来源:https://stackoverflow.com/questions/8055605/identity-expression-factor-and-term

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!