Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a macro and a function in C? [closed]

Tags:

What is the difference between a macro and a function in C? Please tell me one application where I can use macros and functions?

like image 367
user615929 Avatar asked Feb 14 '11 09:02

user615929


People also ask

What is the use of a macro instead of using a function?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.

Can we use macro for function in C?

In C, function-like macros are much similar to a function call. In this type of macro, you can define a function with arguments passed into it. TechVidvan Tutorial: Macros with arguments! In the above example, the compiler finds the name of the macro (AREA(a)) and replaces it with the statement (a*a).


2 Answers

The basic difference is that function is compiled and macro is preprocessed. When you use a function call it will be translated into ASM CALL with all these stack operations to pass parameters and return values. When you use a MACRO, C preprocessor will translate all strings using macro and than compile.

Minus of using macros is that they hide implementation. Its way harder to find bug if have one.

like image 60
Alexander Sobolev Avatar answered Oct 02 '22 12:10

Alexander Sobolev


In C (and C++) a macro is a preprocessor directive. This means that before your program starts compiling it will go through and process all your macros. Macros are useful because

  • They can make your program easier to read
  • They can improve efficiency (as they can be calculated at compile time)
  • They can shorten long or complicated expressions that are used a lot. For example, we use a macro to get the current log4cpp logger and another few to write to it with various levels.

Disdvatages

  • Expand the size of your executable
  • Can flood your name space if not careful. For example, if you have too many preprocessor macros you can accidentally use their names in your code, which can be very confusing to debug.

Example

#define INCREMENT(x) x++

A function is a piece of code that can relatively independently be executed and performs a specific task. You can think of it sort of like a mathematical function: a function given a set of inputs will give a particular output. In C these are defined as

<return type> <name>(<parameters>)
{
  //code body
}
like image 34
Jim Jeffries Avatar answered Oct 02 '22 13:10

Jim Jeffries