I read there are lexical constants, lexical operators, lexical scope etc. how does the term "lexical" changes the meaning for a constant e.g string literal, for any operator, or a scope of some identifier ?
"lexical" means that it is related to the source code.
For example, 1
is a lexical constant. OTOH, sizeof(char)
is also a compile-time integral constant expression, but it is not a lexical constant. Lexically, it is an invocation of the sizeof
operator.
Lexical operators work on the source code. The preprocessor operators fall into this category.
In most cases, it makes no difference whether I use 1
or sizeof(char)
anywhere in my program. But, as the argument of the lexical operators #
or ##
it makes a considerable difference, because these work on the actual code and not the result of evaluation:
#define STR(x) #x
std::string one = STR(1);
std::string also_one = STR(sizeof(char));
Finally, lexical scope means the portion of the program source code where are identifier exists (is recognized, can be used). This is in contrast to the dynamic scope, also known as object lifetime, which is the portion of the program where the object exists (maintains its value and may be manipulated indirectly via pointer or reference, even though the name is not in lexical scope).
string f(string x) { return "2" + x; } // main's "y" is not in lexical scope, however it is in dynamic scope, and will not be destroyed yet
int main(void)
{
string y = "5.2"; // y enters lexical scope and dynamic scope
string z = f("y"); // y leaves lexical scope as f is called, and comes back into lexical scope when f returns
return z.size();
// z leaves lexical and dynamic scope, destructor is called
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With