1

I want to use a basic macro in C to access a certain Bit b in a char-Array (*char) Arr:

#define TstBit (Arr,b) ( Arr[b/8] & (1 << (b%8)) )  

however upon usage like such:

int foo(const char *charArray) {  
  int readindex = 0;  
  [...]  
    if(TstBit(charArray,readIndex++)) {  

I get an error on the line with the #define-Statement:

main.c | line 7 | error: 'Arr' undeclared (first use in this function)  

I'm suspecting I'm either passing the arguments poorly when calling the Function or that the #define needs some more parentheses.

klutt
  • 30,332
  • 17
  • 55
  • 95
Mark
  • 419
  • 1
  • 6
  • 21
  • 5
    Another problem with this macro, after you've fixed the spaces, is that `TstBit(charArray, readIndex++)` will increment `readIndex` twice, and moreover it has undefined behavior because there is no [sequence point](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) in between the two. This is one of many reasons why you should strongly consider using a function instead (perhaps with `inline`). – Nate Eldredge Jun 17 '20 at 19:11
  • @NateEldredge definetly will do. Not worth the hassle at all. – Mark Jun 20 '20 at 20:23

1 Answers1

2

The space after TstBit seems to be the problem here. The pre-processor, unlike the C compiler, is a bit more fussy about spaces.

With your macro, what the pre-processor does is replace all occurrences of TstBit with (Arr,b) which is not your intention.

#define TstBit(Arr,b) ( Arr[b/8] & (1 << (b%8)) )

should work the way you want.

EDIT: Also note that there is a problem with the way you are trying to use this macro, as noted in this comment!

Macro arguments should ideally not have side-effects. If they do, you should take care that they do not lead to undefined or unintended behaviour.

th33lf
  • 2,177
  • 11
  • 15
  • 1
    As simple as that, indeed. Thanks! – Mark Jun 17 '20 at 19:04
  • It isn't really quite as simple as that, please see Nate's [comment](https://stackoverflow.com/questions/62436396/how-to-properly-define-and-use-parameters-in-c-macro-functions#comment110423045_62436396) that the macro causes *undefined behaviour*. – Weather Vane Jun 17 '20 at 19:24
  • @WeatherVane Thanks! I'll link that comment in my answer as well. – th33lf Jun 18 '20 at 09:31