Macro definition in C and C++

Macro in C: Macros are defined as single identifiers that are equivalent to expressions, complete statement or groups of statements. Macros signify functions in this sense. They are defined in an all together different members than functions. Though, they are treated in a different way during the compilation procedure.

 

Consider the simple c programme

# include < stdio. h >

# define area length * width

Main ()

{

Int length, width;

Print f ("length = ")

Scan f (" % d" & length);

Print f ("width =")

Scan f ("% d", & width);

Print f ("area = % d", area);

}

This programme contains the macro area which represents the expression length & expression and width. When the programme is pile up, the expression length * width will swap the identifier area in the print statement in order that the print f statement will turn out to be

Print f ("area = % d, length * width);

Note the string "area % d" is unaffected by the # define statement. Macro definitions are usually placed at the start of a file, ahead of the first function definition. The scope of a macro definition widen from its point of definition to the ending of the file. A macro defined in one file is not known in other file. Multiline macros can be defined by placing a back ward slash at the end of each line except the last. This feature permits to a single macro (single identifier) to represent a compound statement. Here is another simple C programme that contains a macro:

This programme contains a multiline macro, which represents a compound statement.

Macro in C++: The programme will replace all the macro functions used in programme by their function body before the complication. The feature of macro functions is that there will be no extent function call during execution. Since the function body is substituted at the point of macro call during complications. Thus the runtime overhead for function linking or context switch time is decreased. The macro function spans for a maximum of one line only. 

   Related Questions in Programming Languages

©TutorsGlobe All rights reserved 2022-2023.