How are operators organized in memory

compilerprogramming-languages

How are operators organized/saved in the memory in context of a programming language. Are they procedures/functions saved somewhere and compilers just manipulate things to call these procs whenever the operators are used in the program?

Best Answer

Most operators are just "syntactic sugar" for functions or procedures, so you can look at them mostly the same way:

  • They may be ordinary lists of machine instructions stored at a particular address to be called like an ordinary function. Sometimes these functions are actually callable as normal functions if you know the correct syntax, but in other situations/languages it may be that the compiler handles it completely internally without granting developers access to the functionality through anything but the compiler's own lexer and parser.
  • Sometimes the compiler can replace the operator at the place it is called, in the source, to avoid the overhead of the machine instructions needed for a function call, directly placing the machine code there (i.e. like inlining, in some cases EXACTLY like inlining).
  • Sometimes you might be working in an interpreter / runtime, where the functions are stored in an intermediate language which is "interpreted" by the runtime for the correct machine code, which could conceivably also be inlined but would still need to be interpreted.
  • In some cases, where the operands of the operator are types that are very close or identical to the machine code instruction set the operators may get translated directly into only very few statements. How many statements would mostly depend on whether the operands involved are currently stored in registers or memory (which is a whole compiler topic on its own).
  • In nearly all cases, what actually happens inside the compiler, interpreter or runtime will depend on the types of the operands. An operator between two operands of the same type will end up resolving to the operator for that type (which may or may not be entirely different from the same operator for different types). An operator between operands of different types may be implemented directly (which is rare) or additionally call conversion operators on one or more of the operands to turn them into types that can be operated on, before actually performing the operator itself.