0

A book [1] that I am reading says this:

One of the most interesting developments in programming languages has been the creation of extensible languages—languages whose syntax and semantics can be changed within a program. One of the earliest and most commonly proposed schemes for language extension is the macro definition.

How does a C macro extend the syntax and semantics of the C programming language?

For instance, this macro:

#define BUFSIZE 100

certainly doesn't seem to be extending the syntax and semantics of the C programming language.

Would you give an example (along with an explanation) of a macro that extends the syntax and semantics of the C programming language, please?

[1] The Theory of Parsing, Translation, and Compiling, Volume 1 Parsing by Aho and Ullman, page 58.

Roger Costello
  • 3,007
  • 1
  • 22
  • 43
  • 5
    Does that book specifically mention C macros? Because macro systems in other languages (e.g.: Lisp) work quite differently – UnholySheep May 21 '22 at 12:07
  • Ah! Thanks @UnholySheep in fact the book does not specifically mention C macros. Shall I assume, then, that C macros do not extend the syntax and semantics of the C programming language? – Roger Costello May 21 '22 at 12:10
  • 2
    No. C macros are really just a preprocessing step before compilation. – M Oehm May 21 '22 at 12:19
  • See: [What makes Lisp macros so special?](https://stackoverflow.com/q/267862/2505965) – Oka May 21 '22 at 14:49

1 Answers1

1

Not sure if you can consider this as 'extending' the syntax. C macros can be used in 'hacky ways' to get some different syntax.

A simple example :

#define startmain int main(){
#define endmain }
#define begin {
#define end }

This allows us to write programs like this (something similar to Verilog syntax)

startmain
int i;
for(i=0; i<5; i++) begin
printf("%d\n",i);
end
endmain

But of course, some other languages like LISP have very advanced macro systems that let you do more.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278