fbpx

C++: Inverted Syntax

Bjarne-stroustrup
 


Inverted syntax with conditional expressions

In traditional syntax conditional expressions are usually shown before the action within a statement or code block:

 IF raining=true THEN needumbrella=true

In inverted syntax, the action is listed before the conditional expression in the statement or code block:

 needumbrella=true IF raining=true

Inverted syntax with assignment

In traditional syntax, assignments are usually expressed with the variable appearing before the expression:

 a = 6

In inverted syntax, the expression appears before the variable:

 6 = a

Task

The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.

Though rarely, if ever, used in practice, user-defined class types can have inverted syntax with assignment.

class invertedAssign {
  int data;
public:
  invertedAssign(int data):data(data){}
  int getData(){return data;}
  void operator=(invertedAssign& other) const {
    other.data = this->data;
  }
};
 
 
#include <iostream>
 
int main(){
  invertedAssign a = 0;
  invertedAssign b = 42;
  std::cout << a.getData() << ' ' << b.getData() << '\n';
 
  b = a;
 
  std::cout << a.getData() << ' ' << b.getData() << '\n';
}

It doesn’t work if the left operand is not of the type invertedAssign.

SOURCE

Content is available under GNU Free Documentation License 1.2.