473,748 Members | 3,697 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is the difference between MACRO and FUNCTION?

Where should I use them?

I am giving you my understandings. Please correct me if I am wrong:

MACRO:
e.g.:#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.
Execution is faster. Where will it be stotred?(Is it in bss/stack/?)

FUNCTION:
There will be a overhead due to function arguments. (Aguments are
stored in the stack)

Where MACROs can not be used?
=============== ==========
If the macro defination go like kind of x++ and y++. It's better to
use functions and avoid macros. Use typedef instead of macros (while
pointer declarations).

Where FUNCTIONs can be used?
=============== =========
Anywhere. But RELATIVELY there will be a overhead and takes more CPU
cycles to execute the same. If it's a macro, just simple substitution.

Please throw some light on the above understandings of mine.
-Newbie
Nov 13 '05 #1
7 23554
Newbie_sw2003 <ne***********@ yahoo.com> scribbled the following:
Where should I use them? I am giving you my understandings. Please correct me if I am wrong: MACRO:
e.g.:#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.
Correct. The compiler is not even aware that there was a macro. All
it sees is the substituted value.
Execution is faster. Where will it be stotred?(Is it in bss/stack/?)
The C standard does not define "bss", "stack", or any other storage.
It could be carved in stone if the implementation so wishes.
FUNCTION:
There will be a overhead due to function arguments. (Aguments are
stored in the stack)
There will also be overhead because of the function itself. Calling
a function is an operation that takes up time. Again, no specific
storage is defined by the standard.
Where MACROs can not be used?
=============== ==========
If the macro defination go like kind of x++ and y++. It's better to
use functions and avoid macros. Use typedef instead of macros (while
pointer declarations).
Macros can't be pointed to either. You can give functions as
parameters to other functions, but not macros.
Also, macros can do things typedefs can't.
Where FUNCTIONs can be used?
=============== =========
Anywhere. But RELATIVELY there will be a overhead and takes more CPU
cycles to execute the same. If it's a macro, just simple substitution.
Functions also have their own variable scope, so they have their own
local variables. Functions also have a proper notion of arguments, while
macros only use textual substitution.
Please throw some light on the above understandings of mine.
-Newbie


--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Life without ostriches is like coffee with milk."
- Mika P. Nieminen
Nov 13 '05 #2
Joona I Palaste wrote:
The C standard does not define "bss", "stack", or any other storage.
It could be carved in stone if the implementation so wishes.


Who know, maybe nanocomputers will someday store data by removing
atoms of silicon from a surface...

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk. pbz' | rot13
Nov 13 '05 #3
In <bj**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
Newbie_sw200 3 <ne***********@ yahoo.com> scribbled the following:
Where should I use them?
I am giving you my understandings. Please correct me if I am wrong:

MACRO:
e.g.:#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.


Correct.


???
The compiler is not even aware that there was a macro.
For the simple reason that there was no macro at all.
All it sees is the substituted value.


No macro, no substitution. Only a syntax error requiring a diagnostic.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #4
Dan Pop <Da*****@cern.c h> scribbled the following:
In <bj**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
Newbie_sw20 03 <ne***********@ yahoo.com> scribbled the following:
Where should I use them?

I am giving you my understandings. Please correct me if I am wrong:

MACRO:
e.g.:#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.


Correct. ??? The compiler is not even aware that there was a macro. For the simple reason that there was no macro at all. All it sees is the substituted value.

No macro, no substitution. Only a syntax error requiring a diagnostic.


There I was, looking for some sense in Dan's reply, when it struck me.
The hyphen (-) is an illegal character in macro names, therefore Dan, in
his usual cryptic form, is right. The code would have to read:
#define ref_name 99

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"No, Maggie, not Aztec, Olmec! Ol-mec!"
- Lisa Simpson
Nov 13 '05 #5
Newbie_sw2003 wrote:
e.g.:#define ref-name 99


'-' is not a legal character for C identifiers. Just A-Z a-z 0-9 and
'_'.

--
Tom Zych
This email address will expire at some point to thwart spammers.
Permanent address: echo 'g******@cbobk. pbz' | rot13
Nov 13 '05 #6
In <bj**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
Dan Pop <Da*****@cern.c h> scribbled the following:
In <bj**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:

Newbie_sw200 3 <ne***********@ yahoo.com> scribbled the following:
Where should I use them?

I am giving you my understandings. Please correct me if I am wrong:

MACRO:
e.g.:#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.

Correct.
???

The compiler is not even aware that there was a macro.
For the simple reason that there was no macro at all.

All it sees is the substituted value.

No macro, no substitution. Only a syntax error requiring a diagnostic.


There I was, looking for some sense in Dan's reply, when it struck me.
The hyphen (-) is an illegal character in macro names, therefore Dan, in
his usual cryptic form, is right. The code would have to read:
#define ref_name 99


The harder you work to find a mistake, the less is the likelihood of ever
repeating it ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #7


On 9/10/2003 6:05 AM, Joona I Palaste wrote:
Newbie_sw2003 <ne***********@ yahoo.com> scribbled the following:
Where should I use them?


I am giving you my understandings. Please correct me if I am wrong:


MACRO:
e.g.:#defin e ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.

Correct. The compiler is not even aware that there was a macro. All
it sees is the substituted value.

Execution is faster. Where will it be stotred?(Is it in bss/stack/?)

The C standard does not define "bss", "stack", or any other storage.
It could be carved in stone if the implementation so wishes.


If "it" is the macro definition (as opposed to the invocation), it isn't stored.
The preprocessor expands the macro definition in-line so to the compiler it's
just more text within the function or wherever you happen to have placed the
macro invocation.
FUNCTION:
There will be a overhead due to function arguments. (Aguments are
stored in the stack)

There will also be overhead because of the function itself. Calling
a function is an operation that takes up time. Again, no specific
storage is defined by the standard.

Where MACROs can not be used?
============= ============
If the macro defination go like kind of x++ and y++. It's better to
use functions and avoid macros. Use typedef instead of macros (while
pointer declarations).

Macros can't be pointed to either. You can give functions as
parameters to other functions, but not macros.
Also, macros can do things typedefs can't.

Where FUNCTIONs can be used?
============= ===========
Anywhere. But RELATIVELY there will be a overhead and takes more CPU
cycles to execute the same. If it's a macro, just simple substitution.

Functions also have their own variable scope, so they have their own
local variables. Functions also have a proper notion of arguments, while
macros only use textual substitution.


I know you know this, but for the OP: macros CAN have their own scope too, if
you define them as such, e.g.:

#define PRTHELLO() do { \
char *_x = "hello"; \
puts(_x); \
} while (0)

Notes:

1) The underscore in front of the variable name - since macros are expanded
in-line, it's good to have a naming convention for variables declared within the
macro that at least attempts to separate them from the variables declared in a
calling function.

2) The backslashes at the end of each line - unlike a function, a macro
definition ends at the end of the line, so to let you split your text over
multiple lines for ease of reading, you need to escape the end of lines.

3) The { ... } - this creates the scope for local variable declarations AND
bug-proofs the code so that if someone wrote a multi-statement macro and then
put it inside an "if" with no braces, the whole body would be considered as one
block. e.g. if I define 2 macros:

#define DOAB() \
a(); \
b()

#define DOXY() { \
x(); \
y(); \
}

if (condition1)
DOAB();

if (condition2)
DOXY();

then this will expand to:

if (condition1)
a();
b(); /* NOTE: b() is no longer within the "if"
* and so will be executed unconditionally !
*/

if (condition2)
{
x();
y();
};

so if condition1 is fales, b() will still get executed.

4) The do ... while(0) - this forces callers of the macro to put a semi-colon at
the end. In the example above I had

if (condition2)
DOXYZ();

but that trailing semicolon is actually unnecessary as you can see from the
expanded version above and can in fact cause problems. By changing the
definition to:

#define DOXY() do { \
x(); \
y(); \
} while(0)

this expands to:

if (condition2)
do {
x();
y();
} while(0);

which does now require that trailing semi-colon. One advantage of requiring the
semicolon on the invocation is that you could in future replace the text in the
macro definition with a function call and not have to worry about potentially
introducing errors in the code of callers who had/hadn't been relying on not
needing that semicolon. For more info on "do ... while(0)", see the comp.lang.c
FAQ http://www.eskimo.com/~scs/C-faq/q10.4.html

5) The macro name is all upper-case - that's a pretty normal convention for
user-defined macros whereas function names are typically a mix of upper/lower case

6) Macros should be kept small - a rough rule of thumb for macros vs functions
is to only use macros if the code size is small (less than, say, 20 or so lines)
and you can't afford the function call real-time overhead.

Ed.
Please throw some light on the above understandings of mine.
-Newbie



Nov 13 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

220
19112
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
2
5732
by: Aakash Jain | last post by:
Can someone explain me the difference between the following C++ macro and the function MAX: #define MAX(a, b) (((a) > (b)) ? (a) : (b)) template <class T> const T& MAX(const T& a, const T& b) { return (a > b ? a : b); }
7
1971
by: sachin_mzn | last post by:
Hi, It may be a silly question but I want to know the difference between #define macro and inline functions Is there any performance issue related to it. -Sachin
8
10864
by: lasek | last post by:
Hi...in some posts i've read...something about using macro rather then function...but difference ??. Best regards....
23
1917
by: yezi | last post by:
Hi, all: The 1st sendtence: int main(){ char string={""}; string = {" connected "}; ..... }
17
2049
by: zhangyue.zl | last post by:
static void (DEVICE_REQUEST)(void); What does this line declare in C? I am always meeting some codes like this,but I have never learnt that before. It looks like a declaration of a function,but why DEVICE_REQUEST has to be quoted by ( ). Anyone can explain that to me? thanks a lot!
11
22370
by: San | last post by:
hi there, I am new to c++ and tryig to learn the basics of the c++ concepts. While I was reading the templates, I realize that the templates are a syntax that the compilar expands pased upon the type specified. This is much similar like a macro expansion in C. can anyone please explain advantages of one over the other ? Thanks in advance -
21
2319
by: MAx | last post by:
Hi, Could any one list possible number of diferences between a function and a macro? which one will be faster and why?? ex : function and a macro ti find max of two nums #define MAX(a,b) (a>b) ? a:b and int max(int a,int b)
6
2311
by: jason | last post by:
Hi, I learned my lesson about passing pointers, but now I have a question about macros. Why does the function work and the MACRO which is doing the same thing on the surface, does not work in the following small example ? #include <stdio.h>
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9319
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.