Reputation: 2516
I wrote this macro for searching number in array:
#define FIND(VALUE,ARR,INDEX){\
int i;\
INDEX = -1;\
for(i = 0;i <sizeof(ARR)/sizeof(VALUE); i++){\
if(ARR[i] == VALUE){\
INDEX = i;\
}\
}\
\
}
My questions is, will it be a problem if I define int i
in the macro and also in the main?
Upvotes: 0
Views: 64
Reputation: 40625
Of course, the i
is only a problem, if you get i
passed in to your macro as a parameter, because macros do pure text substitution.
Apart from that, there are several issues with your code:
The idiomatic way to wrap a void-function like macro is to use a do { ... } while(0)
loop. Only that swallows semicolons correctly.
You have not wrapped all your parameters in parentheses as you should. If you pass 7 & foo
as VALUE
, the expression if(ARR[i] == VALUE){
will expand to if(ARR[i] == 7 & foo){
, which won't do what you expect.
Your macro parameters are evaluated several times, so your code will explode if you pass something like foo++
for any of them.
The element count calculation sizeof(ARR)/sizeof(VALUE)
is plain wrong. There is no guarantee that the type of VALUE
is the same as the element type of the array. If you calculate an array element count in a macro, always used sizeof(ARR)/sizeof(*ARR)
.
Upvotes: 1
Reputation: 2447
It will not be a problem, even you redefine i
in main
.
#define FIND(VALUE,ARR,INDEX){\
int i;\
INDEX = -1;\
for(i = 0;i <sizeof(ARR)/sizeof(VALUE); i++){\
if(ARR[i] == VALUE){\
INDEX = i;\
}\
}\
\
}
Since you defined a own scope '{' within the macro.
Upvotes: 0
Reputation: 50667
It's OK. The i
in the macro will be only visible in the macro, and will also hide outer i
within this macro scope.
Upvotes: 0
Reputation: 46960
No. The inner block will hide the outer. However there will be a problem if the INDEX
passed in is i
. This is why you frequently see weird variable names like _i_
used in macros. It's an attempt to avoid name clashes.
With modern compilers and hardware, there is little reason to fiddle with macros in his manner. Just use a function.
Upvotes: 2
Reputation: 70931
The i
in the macro will hide any other i
declared either in the surrounding context or globally. Whether one regards this as a problem or not depends on the need to be able to access the hidden i
.
Upvotes: 4