1

I've had a series of bugs over the last month due to mistyping of "&" instead of "&&" in C.

My latest one was simple - i.e. I wrote

value = data && 0x0123

It was obvious after I hit a break and saw the value was 0 or 1, but I want a way to catch this earlier, similar to coding

if (1 == END) ... 

to catch misuse of = and ==.

Any ideas?

15
  • 2
    Just write good code?! It's simple
    – Rizier123
    Jan 13, 2015 at 19:45
  • 4
  • 6
    Since you tagged C++: in C++ you can use and and bitand instead of && and &. See here
    – Borgleader
    Jan 13, 2015 at 19:46
  • 2
    Can't say I've ever had this problem. Jan 13, 2015 at 19:54
  • 2
    @LightnessRacesinOrbit is right. It doesn't make sense to make that mistake unless you didn't know the difference between & & && and now you found out, and don't want to search your code for such issues, I would recommend using grep to search for all possible occurrences of both & & && and fix each one. Jan 13, 2015 at 19:56

1 Answer 1

8

In C++, and and bitand are alternatives for && and & respectively (You can find all the alternatives on cppreference).

#include <iostream>

int main()
{
    std::cout << std::boolalpha << (42 and 0x0123) << std::endl;
    std::cout << std::boolalpha << (42 bitand 0x0123) << std::endl;
    return 0;
}

Live on Coliru (Thanks to Fred Larson for the std::boolalpha suggestion)

C99 defines these as macros in iso646.h (Credit goes to Shafik Yaghmour, more details in one of his answers)

5
  • 2
    Since the question is also tagged C, you should also explain that iso646.h is needed. Note, I am not the downvoter. Jan 13, 2015 at 19:56
  • I think adding std::boolalpha makes your example code even more obvious. Jan 13, 2015 at 19:57
  • It might be worth noting that or and bitor can be substituted for || and | respectively as well. Jan 13, 2015 at 20:08
  • @FredLarson Added a link to the cppreference page, it has a table with all of them.
    – Borgleader
    Jan 13, 2015 at 20:10
  • 1
    <iso646.h> was actually added to C by an amendment in 1995 (ANSI/ISO/IEC 9899-1990-AM 1-1995), so pre-C99 compilers are likely to support it. Jan 13, 2015 at 23:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.