Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the term "lexical" means in C++?

Tags:

c++

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 ?

like image 467
user103214 Avatar asked Nov 07 '11 21:11

user103214


1 Answers

"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
}
like image 83
Ben Voigt Avatar answered Oct 23 '22 23:10

Ben Voigt