Roger Costello
Roger Costello

Reputation: 3209

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

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.

Upvotes: 0

Views: 99

Answers (1)

Praveen Kumar S
Praveen Kumar S

Reputation: 31

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.

Upvotes: 1

Related Questions