Pages

Tuesday, 15 November 2022

Chapter 25 // Exercise 4 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.

Chapter 25 // Exercise 4

Add the bitwise logical operators &, |, ^, and ~ to the calculator from chapter 7.


Just when you thought it was safe, chapter 7 returns. I last touched that code 3 years ago now according to GitHub. I remember absolutely hating tokens and token streams because I thought they were some weird special type...it's just a class that gets characters from the cin buffer lol. I really love going back to old exercises as it makes me realise that I have learnt something after all.

I decided to go with the finished code from exercise 9:

And started by cleaning it up and putting it into seperate files. Then I added the bitwise operators  to my enum of symbols.

Now, as per the rules of the calculator, &, | and ^ are all expressions as they need primary's to operate on. However ~ is a prefix and can be used by itself so that makes it a primary. The main problem though is that you can't use (or shouldn't be using) bitwise operators on doubles as they're made up of 3 parts and our Tokens store all values as doubles.

To get round this I just cast everything to an int and then perform the operations but it prints a warning if the double wasn't safely converted to a float using std::modf();

I also made it so NOT requires parenthesis around the expression so you can do things like ~(5+4+sqrt(25)).

Chapter 25 // Exercise 4 - Principles & Practice Using C++


No comments:

Post a Comment