return (a) vs. return a - c++

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);

Related

Eigen: Comparing each element of vector with constant

is there a way how to compare each element of a vector with a constant? So far, I am comparing 2D vector Eigen::Vector2d with a constant double tolerance like this:
if (x(0) > tolerance && x(1) > tolerance)
{
...
}
I have found the function isApprox() but it did not worked somehow. Is there is a nicer or recommended way on how to do it?
One way to do this is to use the array method of the Vector class. Like this:
#include <Eigen/Dense>
#include <iostream>
int main(int argc, char * argv[]) {
Eigen::Vector2d A{ 7.5, 8.2 };
std::cout << A << '\n';
auto res = A.array() >= 8.0;
std::cout << res << '\n';
if (res.all()) {
std::cout << "True" << '\n';
}
else {
std::cout << "False" << '\n';
}
A(0) = 10.2;
auto res2 = A.array() >= 8.0;
std::cout << res2 << '\n';
if (res2.all()) {
std::cout << "True" << '\n';
}
else {
std::cout << "False" << '\n';
}
return 0;
}
In this case res and res2 are CwiseBinaryOp which contains booleans for each element in A. Use all to find when both are True.
I feel like a good call on this one is to write a simple function:
bool is_componentwise_greater_than(
Eigen::Ref<Eigen::VectorXd const> const &vector, double lower_bound) {
for (auto value : vector) {
if (value <= lower_bound)
return false;
}
return true;
}
The drawback of this way compared to the solution by #Matt is, that for more complicated use cases, using an Eigen expression can be more performant (no idea, if this applies here).
The (in my opinion huge) advantage of such an solution is, that you
can see exactly what it does from its usage.
Of course you can also pack Matts solution in an aptly named function to get this advantage. Another advantage is, that with the function I provided you know exactly what it does and never have to wonder, whether using auto with an Eigen type could bite you. I guess it won't and Matt probably knows exactly why. But I (and you?) do not and therefore wouldn't want to rely on it.

Write a function that will swap two integers using refrences

This is a particularly strange question, but i'm attempting to write a function that swaps the values of two integers without using references or '&'. I don't see how this is even possible. Here's what I have so far.
void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
This, normally would be the way that I would do it, but since the integers don't permanently change, I have no idea as to how I would do this without referencing. Any suggestions?
Thanks!
You should correct the question title. It says “using references”. That’s the opposite of what you mean, apparently.
Assuming that:
truly no references and pointers allowed, exluding any wrapper tricks
a runtime swap is what you want – as opposed to compile time template trickery
no classes, because that would trivial
I can think of one utterly horrible solution. Make your ints globals.
ridiculous_swap.hpp
#ifndef RIDICULOUS_SWAP_HPP
#define RIDICULOUS_SWAP_HPP
extern int first;
extern int second;
void swap_ints();
#endif // RIDICULOUS_SWAP_HPP
ridiculous_swap.cpp
int first = 0;
int second = 0;
void swap_ints()
{
auto tmp = first;
first = second;
second = tmp;
}
main.cpp
#include "ridiculous_swap.hpp"
#include <iostream>
int main()
{
first = 23;
second = 42;
std::cout << "first " << first << " second " << second << "\n";
// prints: first 23 second 42
swap_ints();
std::cout << "first " << first << " second " << second << "\n";
// prints: first 42 second 23
}
It’s not useful for anything, but it does swap two integers without using references or pointers.
There is this old trick to swap two integer-like variables without using a temporary variable:
void swap(int& a, int& b)
{
a ^= b;
b ^= a; // b ^ (a ^b) = a
a ^= b; // (a ^ b) ^ a = b
}

Dev c++ 5.11 on Windows 8 Produces wrong answer

#include<iostream>
#include<conio.h>
class Number
{
private:
int x, y;
public:
Number()
{
x = y = 100;
}
void avg()
{
std::cout<<"x = "<<std::cout<<x;
std::cout<<std::endl;
std::cout<<"Y = "<<std::cout<<y;
std::cout<<std::endl;
std::cout<<"Average = "<<std::cout<<(x+y)/2;
}
};
main()
{
Number n;
n.avg();
}
This programme runs but shows wrong answer, may be showing addresses of memory locations instead of showing the assigned values of 100. Please correct me why it is behaving like this?
std::cout << "x = " << std::cout << x;
is wrong. You need
std::cout << "x = " << x;
Otherwise, the std::cout stream object in ...<< std::cout is implicitly converted to a (void*) when invoking operator<< on it, and therefore the pointer (an address) is displayed.
The conversion to void* exists for historic reasons (the safe bool idiom), but in C++11 was removed, due to the introduction of explicit conversion operators, so your code should not compile in C++11.

Writing reference declaration and assignment in same statement

Is there anything wrong with writing a reference declaration and assignment in one statement. I have tried it using gcc and it seems to work.
int x = 10;
cout << "x = " << x << "\n";
int &y = x = 11;
cout << "x = " << x << "\n";
cout << "y = " << y << "\n";
gives me the expected output
x = 10
x = 11
y = 11
Is this expected to work on most compilers or will there be a portability issue?
In C++, there is an assignment operator, which can be used (at least in
principle) in any expression. Note that in:
int& y = x = 11;
The first = is not an operator; it is part of the syntax of the data
definition. What follows this = is an expression, which must result
in an lvalue of type int. Since x is an int, x = 11 has type
int. And the result of the built-in assignment operator is an lvalue,
referring to the object which was the target of the assignment, so
you've met the necessary conditions.
Of course, that doesn't mean that it's good code.

Why do different C++ compilers give different results for this code?

I'm writing some C++ codes for fun and practice, to learn more about language features. I want to know more about static variables and their behaviour in recursive functions. Trying this code in g++ compiler, I'm given expected result:
#include <iostream>
using namespace std;
int f(const int& value)
{
static int result = 0;
return result += value;
}
int main()
{
cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10)));
return 0;
}
But my friend tested same code in Microsoft Visual C++ 6. output is 50, 80, 90 I tested it with other C++ compilers (g++, Borland, Code::blocks and MingW under Linux, Win and Mac) output was 110, 100, 40. I can't understand how output could be 50, 80, 90 ...
Why MSVC's output is different?
The order of evaluation of the following three subexpressions is unspecified:
f(10)
f(f(10))
f(f(f(10)))
The compiler may evaluate those subexpressions in any order. You should not rely on a particular order of evaluation in your program, especially if you intend to compile using multiple compilers.
This is because there is no sequence point anywhere in that expression. The only requirement is that each of those subexpressions is evaluated before the result is needed (that is, before the result is to be printed).
In your example, there are actually several subexpressions, which I've labelled as a through k here:
// a b c d e f g h i j k
cout << f(10) << ", " << f(f(10)) << ", " << f(f(f(10)));
The calls to operator<< (a, c, d, g, and h) all have to be evaluated in order because each depends on the result of the previous call. Likewise, b has to be evaluated before a can be evaluated, and k has to be evaluated before j, i, or h can be evaluated.
However, there are no dependencies between some of these subexpressions: the result of b is not dependent upon the result of k, so the compiler is free to generate code that evaluates k then b or b then k.
For more information on sequence points and related unspecified and undefined behavior, consider reading the Stack Overflow C++ FAQ article, "Undefined Behavior and Sequence Points" (your program doesn't have any undefined behavior, but much of the article still applies).
Just because the output appears left-to-right on the screen does not mean the order of evaluation follows the same direction. In C++, the order of evaluation of function arguments is unspecified. Plus, printing data via the << operator is just fancy syntax for calling functions.
In short, if you say operator<<(foo(), bar()), the compiler can call foo or bar first. That's why it's generally a bad idea to call functions with side effects and use those as arguments to other functions.
An easy way to see exactly what it is doing:
int f(const int& value, int fID)
{
static int result = 0;
static int fCounter = 0;
fCounter++;
cout << fCounter << ". ID:" << fID << endl;
return result += value;
}
int main()
{
cout << f(10, 6) << ", " << f(f(10, 4), 5) << ", " << f(f(f(10, 1),2),3);
return 0;
}
I agree with what others have said in their answers, but this would allow you to see exactly what it is doing. :)
The prefix operator syntax is translated into the following prefix notation:
<<( <<( <<( cout, f(10) ), f(f(10)) ), f(f(f(10))) )
A B C
Now there are three different function calls, identified as A, B and C above. with the arguments of each call being:
arg1 arg2
A: result of B, f(10)
B: result of C, f(f(10))
C: cout , f(f(f(10)))
For each one of the calls, the compiler is allowed to evaluate the arguments in any order, for the correct evaluation of the first argument of A, B has to be evaluated first, and similarly for the first argument of B, the whole C expression has to be evaluated. This implies that there is a partial order on the execution of A, B, and C required by the first argument dependency. There is also a partial ordering on the evaluation of each call and both arguments, so B1 and B2 (referring to the first and second arguments of the call B) have to be evaluated before B.
Those partial orderings do not lead to a unique requirement for the execution of the calls, since the compiler can decide to execute all second arguments before trying to evaluate the first argument, leading to the equivalent path:
tmp1 = f(10); tmp2 = f(f(10)); tmp3 = f(f(f(10)));
cout << tmp1 << tmp2 << tmp3;
or
tmp3 = f(f(f(10))); tmp2 = f(f(10)); tmp1 = f(10);
cout << tmp1 << tmp2 << tmp3;
or
tmp2 = f(f(10)); tmp1 = f(10); tmp3 = f(f(f(10)));
cout << tmp1 << tmp2 << tmp3;
or ... keep combining.