tags:

views:

133

answers:

3

is there a way to define std::string and std::stringstream inside if or main function as a parameter

example

main(int d,int m)
{
if(std::cin>>d)
{}
if(std::stringstream ss,std::string s)
{}


}

it is giving the error

expected primary-expression before ‘ss’
error: expected `)' before ‘ss’
A: 

Anything returning any value like any function call can be done inside if but you can not declare variables in that, really silly.

This can be done as printf will return some value and if will check that return value for condition

 if(printf("Hello"))

but not this

if(std::string str)
Vivek
-1, wrong. This is valid: `if(int fooResult = foo()) { ... }`. Works for any type that converts to `bool`
MSalters
Here you are using a variable to save return type and then check that return type in if statement which is similar to what I have written in first if statement and what I said is that if(std::string str) is invalid and not anything like if(int a=getInt()). Understand first what I said and thrn comment as if(std::string str) and if(int fooResult = foo()) are different if statements
Vivek
+3  A: 

As this is C++ main must have a return type in it's declaration. The actual error that you are getting seems to indicate that you need to #include <sstream> at some point.

While you can declare a variable inside an if's condition expression it's not a feature that's used very often and the one object that's constructed must have an valid implicit conversion sequence to a bool. You can't use a , to attempt to declare two variables, it's not a valid expression for an if clause.

If construction of any object fails then an exception will have to have been thrown so this isn't a necessary or correct way to test for construction failure. You should probably just declare your variables in the function scope of main.

Charles Bailey
in C++ the "return 0" statement of the main function is implicit: http://www2.research.att.com/~bs/bs_faq2.html#void-main
lx
@lx: Thanks for spotting the unclear wording. I meant something entirely different which I've fixed in my edit.
Charles Bailey
A: 

The only valid pattern is:

Base* b = ...;
if (Derived* d = dynamic_cast<Derived*>(b)) {
  d->stuff();
}
Benoît