Thread: A beginner question on how to use a variable as an operator

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    1

    Question A beginner question on how to use a variable as an operator

    I have a question could a variable act as an operator such as "+" to add two numbers if so how do i write that? so what I would like to do would be answer = (a b c)
    where a is some number b is an operator (such as +) and c is another number, Im not sure how to write that so i could get that line to work and help would be really appreciated

    basically trying to a calculator without all the cases
    Last edited by DawnOfMe; 09-04-2015 at 02:00 PM.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Sorry, but that capability does not exist in C++. You might find it in a dynamically-typed language, although I can't think of one that would allow that.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    Can you explain more why you want the "variable as an operator"?

    Soma
    “Salem Was Wrong!” -- Pedant Necromancer
    “Four isn't random!” -- Gibbering Mouther

  4. #4
    spaghetticode
    Guest
    What Elkvis said. Not possible in C++, you need a workaround with an if-statement, for example.

    Code:
    if (b == '+') {
        answer = a + b;
    } else if (b == '-') {
        answer = a - b;
    } else ...
    Last edited by spaghetticode; 09-08-2015 at 02:07 AM. Reason: typo

  5. #5
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by spaghetticode View Post
    ...with an if-statement, for example.
    That's what the OP was hoping to avoid.

    Interestingly enough, there's a library available for GCC (C/C++ compiler) called libgccjit, that allows you to generate executable code programmatically, so you could have your calculator take its input, then generate a function based on that input, then call it, and get the result. Much more complex than using switch or if...else if.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by Elkvis View Post
    Sorry, but that capability does not exist in C++. You might find it in a dynamically-typed language, although I can't think of one that would allow that.
    You could do it in any language that can interpret its own code as a runtime script (C# could do this, for example, with the Roslyn compiler or CS-Script). Here, your main program would substitute the value of b (i.e. it would create the string "answer = a + c") and then execute that string as code.

    That said, I certainly wouldn't use that approach in C#. That would make the solution more complex, not less.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  7. #7
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Just for funsies, this is how you do it:

    Code:
    int main()
    {
    	int x, y;
    	std::cout << "Enter two numbers: ";
    	std::cin >> x >> y;
    
    	char Op;
    	std::cout << "Enter op (+ or -): ";
    	std::cin >> Op;
    	
    	typedef int(__fastcall OpFnc_t)(int, int);
    	uint8_t Code[] = { 0x8b, 0xc1, 0x00, 0xc2, 0xc3 };
    	uint8_t OpTable['-' + 1];
    	OpTable['+'] = 0x03;
    	OpTable['-'] = 0x2B;
    	Code[2] = OpTable[Op];
    	auto * CodeBuf = VirtualAlloc(nullptr, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    	memcpy(CodeBuf, Code, sizeof(Code) / sizeof(Code[0]));
    	OpFnc_t* OpFnc = (OpFnc_t*)CodeBuf;
    
    	int z = OpFnc(x, y);
    	std::cout << z << "\n";
    }
    Compiles and runs on VS2015. This goes without saying, but... DON'T DO THIS IN YOUR PRODUCTION CODE. This is just for fun.

    https://youtu.be/UL3FHtCq97U
    Last edited by Elysia; 09-09-2015 at 11:57 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  8. #8
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    Quote Originally Posted by Elysia View Post
    Just for funsies, this is how you do it:

    Code:
    int main()
    {
    	int x, y;
    	std::cout << "Enter two numbers: ";
    	std::cin >> x >> y;
    
    	char Op;
    	std::cout << "Enter op (+ or -): ";
    	std::cin >> Op;
    	
    	typedef int(__fastcall OpFnc_t)(int, int);
    	uint8_t Code[] = { 0x8b, 0xc1, 0x00, 0xc2, 0xc3 };
    	uint8_t OpTable['-' + 1];
    	OpTable['+'] = 0x03;
    	OpTable['-'] = 0x2B;
    	Code[2] = OpTable[Op];
    	auto * CodeBuf = VirtualAlloc(nullptr, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    	memcpy(CodeBuf, Code, sizeof(Code) / sizeof(Code[0]));
    	OpFnc_t* OpFnc = (OpFnc_t*)CodeBuf;
    
    	int z = OpFnc(x, y);
    	std::cout << z << "\n";
    }
    Compiles and runs on VS2015. This goes without saying, but... DON'T DO THIS IN YOUR PRODUCTION CODE. This is just for fun.

    https://youtu.be/UL3FHtCq97U
    Wow. That has to be the jankiest way I've ever seen of embedding assembly (or rather, machine) language instructions. I am equal parts impressed and horrified
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  9. #9
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by DawnOfMe View Post
    what I would like to do would be answer = (a b c)
    where a is some number b is an operator (such as +) and c is another number
    You can use function pointers for this. (a b c) is the same as saying b(a,c), where b is a function that performs arithmetic such as adding two numbers. For example, define these two functions:

    Code:
    int op_plus(int a, int b)
    {
        return a+b;
    }
    
    int op_minus(int a, int b)
    {
        return a-b;
    }
    Now the appropriate function can be placed in a function pointer at runtime:

    Code:
    int main()
    {
        int a = 100;
        int c = 200;
    
        cout << "Enter + or -: ";
        char q;
        cin >> q;
    
        typedef int (*FT)(int,int);
        FT b = nullptr;
    
        switch(q) {
        case '+': b = static_cast<FT>(op_plus);
            break;
        case '-': b = static_cast<FT>(op_minus);
            break;
        }
    
        if (b) {
            cout << "answer = " << b(a,c) << endl;
        }
    }
    There are many ways to map your operator input parameter '+', '-', etc into operations. And you'll probably extend and change it as development goes on, so it might be a good idea to move the function pointer stuff into a class:

    Code:
    struct Operation {
        typedef int (*FT)(int,int);
        FT b = nullptr;
    
        Operation(char q)
        {
            switch(q) {
            case '+': b = static_cast<FT>(op_plus);
                break;
            case '-': b = static_cast<FT>(op_minus);
                break;
            }
        }
    
        int operator()(int a, int c) const { return b(a,c); }
        operator int() const { return (int)b; }
    };
    Now the main code becomes:
    Code:
    #include <iostream>
    using namespace std;
    
    /* ... declarations here */
    
    int main()
    {
        int a = 100;
        int c = 200;
    
        cout << "Enter + or -: ";
        char q;
        cin >> q;
    
        Operation b(q);
    
        if (b) {
            cout << "answer = " << b(a,c) << endl;
        }
    }

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,514
    Quote Originally Posted by c99tutorial
    You can use function pointers for this. (a b c) is the same as saying b(a,c), where b is a function that performs arithmetic such as adding two numbers.
    This crossed my mind the first time I read post #1, but the problem is that DawnOfMe was "basically trying to a calculator without all the cases". With a function pointer or function object approach, you still need to "map your operator input parameter '+', '-', etc into operations", and for that you will most likely consider the various cases, whether you literally use a switch with case or an if-else chain.

    Quote Originally Posted by c99tutorial
    And you'll probably extend and change it as development goes on, so it might be a good idea to move the function pointer stuff into a class:
    The static_cast to FT is not necessary. Instead of the conversion function to int, define an explicit conversion function to bool:
    Code:
    explicit operator bool() const
    {
        return b != nullptr;
    }
    Though it might be better to throw an exception from the constructor instead.

    Then again, if you are going with a class, maybe you might as well go with a function object class hierarchy.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner's question: const operator++() ?
    By yaraeovento in forum C++ Programming
    Replies: 2
    Last Post: 05-21-2013, 02:35 PM
  2. Replies: 18
    Last Post: 02-18-2013, 11:46 PM
  3. Unused Variable - Beginner Question
    By intex in forum C Programming
    Replies: 4
    Last Post: 11-24-2012, 07:25 PM
  4. Beginner Question about OR operator
    By Enthusiast in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2011, 09:04 PM
  5. increment operator Question from a beginner
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 12-05-2001, 08:23 AM

Tags for this Thread