views:

264

answers:

3

Given the expression by input like 68+32 we have to evaluate without using a semicolon in our program. If it will be something inside the if or for loop? Reference : https://www.spoj.pl/problems/EXPR2/

+4  A: 

You can use constructs like this:

if (i++) {}

However, that still doesn't answer how to declare variables. However, one trick you can do is:

#include <iostream>

int main(double x, double y) {
    if ((x = 1)) {}
    if ((y = 2)) {}
    if (std::cout << x << ", " << y << std::endl) {}
}

Sure, you'll get warnings for using the wrong types in the main argument list, but it'll work.

Joey Adams
can we declare a variable inside if.
prateek
+1 for flouting convention of main's parameters.
wallyk
You can declare a variable inside an "if", but it will only exist in the scope of that "if".
Shmoopty
sir i am getting problem in handling string using stringstream.
prateek
+5  A: 

You can use if and the comma operator, something like this:

if( expr1, expr2, expr3, ... ) {}

It would be equivalent to

expr1;
expr2;
expr3;
...

To use variables without any warnings you can define a function the recieves the data types you need that you call from your main, like so:

void myFunc(int a, double b) {
    if ( expr1, expr2 ) { }
}
int main() {
    if ( myFunc(0, 0), 0 ) { }
}

Note that you need to add , 0 in main, otherwise an error is raised because a void return is not ignored.

Juan
A: 

I'm not a big fan of doing people's work for them (this looks a lot like a homework problem), but to give you an idea of the general pattern to follow, begin by writing your code using semicolons:

main() {
    int firstNumber = getNumber();
    char operator = getOperator();
    int secondNumber = getNumber();
    int result = evaluate(firstNumber, operator, secondNumber);
    Console.writeLine(result);
}

And then replace any variable with the code that was used to generate it:

main() {
    Console.writeLine(
        evaluate(
            getNumber(), 
            getOperator(), 
            getNumber()));
}

Then turn the whole program into one big if statement:

main() {
    if (Console.writeLine(
        evaluate(
            getNumber(), 
            getOperator(), 
            getNumber())) {}
}

Of course, you will need to replace getNumber(), getOperator(), and evaluate() with code that follows this same pattern to read in the values and do stuff with them. I'd recommend you begin by breaking the problem down into individual methods by following the pattern given, and once you've put the whole thing into a single return statement, you can paste the resulting expression in to replace the method call in the main method.

Have fun!

StriplingWarrior
Would someone please tell me why I got voted down? Like the other answers, I didn't totally solve the problem, but I did put some thought into it. Was my answer really that bad?
StriplingWarrior