[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

macro and keyword in CPP and C

Posted on 2014-08-28
9
Medium Priority
?
297 Views
Last Modified: 2014-08-30
Dear Experts,

My question is on  the following testing  C code in test.c

Question-1
keyword of __cpluscplus is stand for the file extension of the running file such as test.c, Right ?
so  test.c file has  c file extension so the following typedef will be active, right ?
#ifndef __cplusplus
typedef unsigned char bool;
static const bool False = 1;
static const bool True = 0;
#endif

Question-2  What is different between defined the function as macro  and define function in the code body ?Any advantage over others ? Both I tested to get the same result.
#define getmax_macro(a,b) ((a)>(b)?(a):(b))
int getmax(int a, int b){}

Please advise

Rwniceing

test.c
======
#include <stdio.h>
#ifndef __cplusplus
typedef unsigned char bool;
static const bool False = 1;
static const bool True = 0;
#endif
#define getmax_macro(a,b) ((a)>(b)?(a):(b))
int getmax(int a, int b){
 if (a>b) 
return a;
else 
 return b;
}
int main()
{
    #if !defined(__BOOL_DEFINED)
        printf("bool is not supported\n");
    #elif defined(__BOOL_DEFINED)
    printf("bool is supported%d\n",__BOOL_DEFINED);
    #endif
	bool arr[2] = {false, true};
	printf("bool is supported%d\n",arr[0]);
	
    int x=5, y;
    y= getmax_macro(x,2);
    printf("getmax_macro: %d\n",y);
    y= getmax(x,2);
    printf("getmax: %d\n",y);
    return 0;
}

Open in new window

0
Comment
Question by:rwniceing
  • 5
  • 2
  • 2
9 Comments
 
LVL 31

Accepted Solution

by:
Zoppo earned 1600 total points
ID: 40289777
Hi rwniceing,

1.) No, the __cplusplus macro is set when the file is compiled with a C++ compiler, if it is compiled with a C compiler it is not set. This doesn't really depend on the file extension (i.e. it's possible to compile a *.c file with a C++ compiler), usually you define what compiler is used for the files in a make file or, i.e. with VisualStudio, in the project files' properties.

2.) The difference is the first one (the macro) is simply a placeholder for the code defined for the macro so that code is compiled directly at the place where you put the macro. The second one is a function which is put anywhere in the binary and called the same way I told you at http://www.experts-exchange.com/Programming/Languages/CPP/Q_28506245.html#a40287844

So the macro here is comparable to a inline function.

Hope that helps,

ZOPPO
0
 
LVL 1

Author Comment

by:rwniceing
ID: 40289789
For question-1: solved
for question-2

macro is defined on preprocessor  from #define, so it will be compiled first before compiling  other function or main() code. Right ? Whereever we put #define on the top of c file or bottom of c file, it will be compiled first, Right ?

So the macro here is comparable to a inline function
in otherwords,  there is no difference between two methods besides compiling priority, right ?

Why not we  put all function code to #define macro instead of inside body ?

It is time to think about preprocessor meaning .


Please advise

Rwniceing
0
 
LVL 31

Assisted Solution

by:Zoppo
Zoppo earned 1600 total points
ID: 40289896
Yes, macros are expanded in a pre-compile step by the preprocessor (http://en.wikipedia.org/wiki/Preprocessor)

When to put functionality into a function or to a macro depends on the need (and a bit on the habit of the programmer).

Macros IMO have some disadvatages compared to functions, i.e.:
- they (at least with IDEs/debuggers I know) cannot be debugged
- it's not possible to overload functions (see http://www.learncpp.com/cpp-tutorial/76-function-overloading/)
- parameters have no type, so i.e. it's not possible to write a SWAP macro
- with functions the compiler can decide whether it's better to use it inlined or not, macros are always inlined and therefor may blow up the code without any benefit.

I for myself in case both macro or function is possible for a needed functionality prefer functions. In a case like your 'getmax' sample this is not the best solution since in this case I would have to implement the same function multiple times for any variable type (i.e. once for int, once for float). In this case I prefer using a function template instead of a macro because types are defined (i.e. with your macro you can compare an int with a float, in a function template you can avoid or allow using different types).

So I would implement such a getmax-functionality as a template somehow like this:
template < typename _TYPE >
_TYPE GetMax( _TYPE a, _TYPE b ) 
{
  return ( a > b ? a : b );
}

Open in new window

So, in other words I only use macros where they are the only method to simplify things which can't be solved another way. A good example for this is a macro to determine the length of a static C-array, i.e.:
#define SIZEOF_ARRAY( x ) ( sizeof( x ) / sizeof( x[0] ) )

double numbers[] = { 1.0, 1.5, 1.8, 2.3, 2.7 };

for ( int n = 0; n < SIZEOF_ARRAY( numbers ); n++ )
{
 cout << numbers[n];
}

Open in new window

Here it's not possible to implement SIZEOF_ARRAY with only one argument as a function instead of a macro.

ZOPPO
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 85

Assisted Solution

by:ozo
ozo earned 400 total points
ID: 40290032
getmax(++a,++b) would work behave differently when called as a macro rather than a function
0
 
LVL 1

Author Comment

by:rwniceing
ID: 40290035
Thanks for your reply and also I found one process flow for compiler process on C/CPP
at this link, https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html#zz-1.4
and described the header file and enable macro file with .i and .ii file extension
0
 
LVL 1

Author Comment

by:rwniceing
ID: 40290040
ozo, in other words, function is more reliable than macro, right ? macro is good for small or simple code that run
faster than a function.

Which method(macro/function) will run faster and use less memory?
0
 
LVL 85

Expert Comment

by:ozo
ID: 40290049
I'm not sure what you mean by reliable.  
You can rely on no more than that both should behave as specified by the language standard.
There are things that can be done with macros and not with functions, and there are things that can be done with functions and not with macros.
There can be situations where a macro will run faster, and there can be situations where a function will run faster.
0
 
LVL 1

Author Comment

by:rwniceing
ID: 40290061
I mean reliable that is  more safe enough to get  the final result from function than macro .
Macro is not  able to be debugged , Right as zoppo mentioned it ?
0
 
LVL 1

Author Closing Comment

by:rwniceing
ID: 40295114
Thanks for your reply
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Suggested Courses

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question