简体   繁体   中英

return (a) vs. return a

I have seen both in the C and C++ code I have been looking at.

What is the difference?

No difference at all.

The official syntax is return something; or return; and of course it is a keyword, not a function.

For this reason you should not read it as return( a ); but as return (a); I think the difference is subtle but clear, parentheses will not apply to return but to a.

((((a)))) is the same as (a) that is the same as a .

You can also write something like...

int x = (((100)));

You can also write something like...

printf("%d\n", (z));

As someone said in the comments, there is now, with C++11 (2011 version of the C++ language) the new operator decltype . This operator introduces a new example where (a) is different from a , this is quite esoteric and a little out of topic but I add this example just for the purpose of completeness.

    int x = 10;
    decltype(x) y = x;   // this means int y = x;
    decltype((x)) z = x; // this means int& z = x;
    y = 20;
    z = 30;
    std::cout << x << " " << y << " " << z << std::endl;
    // this will print out "30 20 30"

Students will not be interested in this, as I said, too esoteric, and it will work only with compilers that supports at least part of the C++11 standard (like GCC 4.5+ and Visual Studio 2010).

This goes in contrast also with the use of typeid keyword:

int a;
std::cout << typeid(a).name() << std::endl; // will print "int"
std::cout << typeid((a)).name() << std::endl; // will print "int" !!!!

Writing return x indicates a programmer who understands what return means. Whereas return(x) indicates a programmer who incorrectly believes that return is a kind of function.

return is not a function.

It is more a point of style. I personally do not use parentheses in a return statement unless it is showing order of operations.

examples

return a;
return (a || b);
return (a && (b || c));
return (a ? b : c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM