Are operators and keywords the same?
I was wondering i开发者_StackOverflow中文版f operators or keywords are the same? If not what is the difference?
Keywords are tokens that are reserved and have a special meaning in a given programming language. Operators are keywords that can take one or more arguments. They are usually associated with the standard mathematical operations, but for example new is considered a single argument operator as well. Operators are usually written in the infix notation (left [operator] right
) and can be nested (taking into account their precedence). Moreover, many languages allow to overload operators, but not necessarily keywords in general.
+
: an operator
new
: a key word, but also an operator
const
: a keyword but not an operator
Broadly, a "keyword" refers to any otherwise valid identifiers (except a few things like literals) that can't be one because it's reserved by the language. (An identifier can be a variable name, class name, namespace name, etc.) keywords are key words, that's all. They might even do nothing, like Java's const
keyword.
An operator is a language element that does something, like addition, parentheses, new
, etc... it may or may not be a word.
Keywords are "words" that have special meaning in the language you are programming in and some of them do some operation and hence operators as well. Like the new keyword which is also an operator.
http://msdn.microsoft.com/en-us/library/kewsb8ba(v=VS.100).aspx
Operators like new are generally considered as "Alphanumeric operator symbols" rather than keywords. Other examples are sizeof
delete
throw
instanceof
I like the way Keywords are defined and handled in Smalltalk:
A keyword: is just an identifier with a colon on the end of it, e.g. anyIdentifierLikeThis: is a {keyword}. In Smalltalk, a keyword is only special in the sense that it forms a "keyword message". It is a distinct kind of token (different from an identifier or a string) but its meaning as an individual token is not special. Some languages have {keywords} like BEGIN and END with builtin special meanings. {Keyword} in Smalltalk is not this sort of thing, it's strictly a syntactic form.
Ther are only six "keywords" that are reserved in Smalltalk: true, false, nil, self, super, and thisContext. So not all keywords are necessarily reserved words in the language.
Reference: http://c2.com/cgi/wiki?SmalltalkTutorial
Regarding true and false:
In some languages like Java, these are boolean literals. In c#, these are both operators and literals. In both cases, these are not considered Keywords. In Smalltalk these are keywords. Really shows how things change from language to language.
Are true and false keywords? True Operator / Literal in C#
精彩评论