Showing posts with label exercise 7. Show all posts
Showing posts with label exercise 7. Show all posts

Tuesday, 27 September 2016

Chapter 6 // Exercise 7 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 6 // Exercise 7

Write a grammar for bitwise logical expressions.  A bitwise logical expression is much like an arithmetic expression except that the operators are ! (not), ~ (complement), & (and), | (or) and ^ (exclusive or).

Each operator does its operation to each bit of its integer operands. ! and ~ are prefix unary operators.

binds tighter than a | (just as * binds tighter than +) so that x|y^z means x|(y^z) rather than (x|y)^z. The & operator binds tighter than ^ so that x^y&z means x^(y&z).

Expression:
    Third Term
    Expression "|" Third Term

Third Term:
    Second Term
    Third Term "^" Second Term

Second Term:
    First Term
    Second Term "&" First Term

First Term:
    Primary
    First Term "!" Primary
    First Term "~" Primary

Primary:
    Object   //int, char, string etc
    "(" Expression ")"


Following the example earlier in chapter 6 I think this is how it would be done although I'm not entirely sure. English was always my best subject but grammar in programming is throwing my brain for a loop.

EDIT 07/10/2019 - This was almost correct the first time I did it. However, now I understand his thought process a little better on grammars I've realised that the First Term section is incorrect. "!" and "~" are always pre-fix operators and as such it will be sufficient for First term to look like this:
Primary
"!" Primary
"~" Primary
This way, they will always affect the Primary instead of the left value. Here is an updated version on GitHub.