8

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 ?

user103214
  • 3,478
  • 6
  • 26
  • 37

2 Answers2

7

"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
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

putting using the term 'lexical constant' doesn't imply a different kind of constant.

Generally, when you are talking about C++ grammar, you will use the term lexical this, lexical that. As opposed to having constants stored in objects, and the scope of a file, or an operator on a matrix.

So if I'm talking about a line of code, which has a constant like: (32786) I can use the word lexical (maybe unnecessarily) to confirm the meaning that the number only exists as a C++ token.

So when I'm talking about C++ tokens and their relationships, I'm using the word lexical like wikipedia does.

marinara
  • 538
  • 1
  • 5
  • 10