C++/c++

Advertisement


Question
hello sir,
i wud like to kno if i can store an operator in a variable eg:x=+ and later use this operator for the operation..like instead of sum=a+b;,can i write sum=a x b;??

Answer
In short no. (note: you could have determined this by just trying it - the compiler would have generated errors for your example code).

Let us examine some possible reasons why C++ does not allow you to do this.

With C++ you use a compiler to compile units of source code into object code (here the use of 'object' is not the same as in 'object oriented programming') usually containing native machine instructions. These object code files are then linked together to form an executable. Once the executable has been built it has no further connection to the compiler or linker.

It is the compiler that contains the logic to parse and evaluate expressions and to turn them into executable sequences of code. This logic is not passed on to the resultant code so the executable has no access to it.

Variables change at runtime, the compiler cannot fully evaluate any expression which contains variables. It can fully evaluate any expression which contains only constant value such as 3*4+2. The compiler can not only parse such an expression to see what operations need to be applied but can also fill in the values of the operands and come up with the result of 14.

On the other hand for an expression such as x * 3 + k the compiler can only supply a sequence of instructions that allow the result to be calculated at runtime once values of x and k are known.

The compiler knows what instructions are performed for these operators because it knows the 'meaning' of * and + when applied to the variables x and k and the integer literal constant 3. This meaning of operators (and even which operators have meaning) is defined by the type of the operands: The meaning of x*3 is determined by the types of x and 3. The meaning of (x*3) + k is given by the resultant type of the expression x*3 and the type of k. If x and k are floating point values then the meaning of the operations is quite different than if they are integer types or some user defined type like std::complex.

Now if not only the operands of an expression are variable but the operators as well as in your sum = a x b example, what code could the compiler possibly generate? How can the compiler check that the operation is sane for the operands used? How can it even generate a correct order in which operations are applied in expressions containing more than one operation? Consider that operators have an order of precedence, in my previous example * is evaluated before + because it has a higher precedence. Thus:

   result = a * b + c;

is equivalent to:

  tmp = a * b;
  result = tmp + c;

On the other hand:

  result = a + b * c;

is equivalent to:

  tmp = b * c;
  result = a + tmp;

If we replace the * and + in the above with operator variable op1 and op2:

   result = a op1 b op2 c;

What is the order of evaluation?

Is it:

  tmp = a op1 b;
  result = tmp op2 c;

or:

  tmp = b op2 c;
  result = a op1 tmp;

It could be either, thus the result is ambiguous at compile time.

I suppose the compiler could try to generate code to cover all possibilities, even those that would be erroneous for the types involved (which brings up another problem: how are errors reported throws an exception presumably, which then has to be handled by your code). However the resultant code would be large, quite possible very large for more complex expressions, which goes against the ideas of efficiency C++ promotes as much as possible.

Such ambiguity also goes against the C++ static (i.e. compile time) type system with the many programmer errors it catches at compile time, where they are best fixed. These include checking that the operators used in expressions apply to the types of the operands. It is always better to have errors reported as early as possible. Compile time if possible, then link time and finally, if you must, run time. This is because you loose context the further away from the problem you get. In fact an error in the code reported at run time (or not it could just terminate or crash the program or cause it to run incorrectly) could occur long after the program has been released and the original developers have moved on.

By the way, have you looked at the table of C++ operators and their order of precedence? It is quite large and daunting see for example http://en.wikipedia.org/wiki/Operators_in_C_and_C++ (The ++ is the end of the URL).

Other than the number of operators and levels of precedence you will note that not all operators apply to all types, some are unary, some are binary; some associate left to right, others right to left. This brings up another point: will only a single operator type suffice? Or should there be a family of such types: one type for binary operators, others for unary. Yet more for those that apply to arithmetic types, those that apply only to integers, those that apply to Boolean expressions etc. etc..

All in all such an operator type (or family of types) would seem to raise more problems than it solves. There is probably another way to do what you were really trying to achieve, whatever it was I cannot work it out from your simple example though.

On the other hand, although not a direct feature of the language, you can create a set of user defined types (in fact type templates) that allow whole expressions to be stored and passed around and evaluated. However this is quite an advanced subject and you will need to have some understanding of C++ templates.

[See:
http://www.angelikalanger.com/Articles/Cuj/ExpressionTemplates/ExpressionTemplat

and

http://osl.iu.edu/~tveldhui/papers/Expression-Templates/exprtmpl.html

for introductions to this subject.]

[For a quick introduction to C++ templates see the tutorial information on cplusplus.com (http://www.cplusplus.com/) at:

http://www.cplusplus.com/doc/tutorial/templates.html.

There is a template FAQ at:

http://womble.decadentplace.org.uk/c++/template-faq.html

and section 35 of the C++ FAQ at:

http://www.parashift.com/c++-faq-lite/

concerns templates.

Finally there is a good reference book: "C++ Templates the Complete Guide" by David Vandevoorde and Nicolai M. Josuttis]

Note: older compilers vary in the quality of their support for templates. Newer compilers are much better but generally still not perfect!

Hope this gives you some insights into C++.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.