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.

2
  • 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 in between the two. This is one of many reasons why you should strongly consider using a function instead (perhaps with inline). Commented Jun 17, 2020 at 19:11
  • @NateEldredge definetly will do. Not worth the hassle at all. Commented Jun 20, 2020 at 20:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

As simple as that, indeed. Thanks!
It isn't really quite as simple as that, please see Nate's comment that the macro causes undefined behaviour.
@WeatherVane Thanks! I'll link that comment in my answer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.