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.
Related
I have this class SmallInt that should represent a positive integer value in the range 0-255-inclusive:
struct SmallInt{
explicit SmallInt(int x = 0) : iVal_( !(x < 0 || x > 255) ? x :
throw std::runtime_error(std::to_string(x) + ": value outbounds!")){}
operator int&() { return iVal_; }
int iVal_;
};
int main(){
try{
SmallInt smi(7);
cout << smi << '\n';
cout << smi + 5 << '\n'; // 7 + 5 = 12
cout << smi + 5.88 << '\n'; // 7.0 + 5.88 = 12.88
smi = 33; // error: constructor is explicit
smi.operator int&() = 33;
cout << smi << '\n';
}
catch(std::runtime_error const& re){
std::cout << re.what() << '\n';
}
}
What matters me is: why can I assign to smi explicitly calling operator int&: smi.operator int&() = 33 but not implicitly: smi = 33;?
The first expression (smi = 33;) complains about the constructor SmallInt(int) begin explicit; I know that but I have the conversion operator that returns a modifiable plain lvalue. So in other words why in such an implicit assignment is the constructor preferred to the conversion operator?
[over.match.oper]/4 For the built-in assignment operators, conversions of the left operand are restricted as follows:
...
(4.2) — no user-defined conversions are applied to the left operand to achieve a type match with the left-most
parameter of a built-in candidate.
Thus (int &)smi = 33 interpretation is explicitly prohibited from consideration by the standard.
Why does this giving compilation problem at bold line?
#include<iostream>
static int i = 10;
int main() {
**(i) ? (std::cout << "First i = " << i << std::endl) : ( i = 10);**
std::cout << "Second i = " << i << std::endl;
}
Compilation message:
test.c:8: error: invalid conversion from ‘void*’ to ‘int’
Your usage of the ternary operator is a bit weird: based on the value of i, you either print something to std::cout or assign a new value to it. Those actions don't share a connection through the return value of an expression, so don't do it like this. When using the ternary operator, it's best to stay closer to its intended purpose: a short notation for two possible expressions with a dispatch based on a simple predicate. Example:
const int n = i == 0 ? 42 : 43;
Your code should look like this:
if (i == 0)
i = 10;
else
std::cout << "First i = " << i << "\n";
The reason the original snippet did not compile is that there is no common return type of the ternary operator. "Common" means that both expressions can be converted to the return type. E.g., in const int n = i == 0 ? 42 : 43; the return type is int.
The problem comes from the fact that the return values of the expressions in your conditional operator (ternary operator) (std::ofstream in the case of the std::cout ..., and int for i = 10) are incompatible and therefore the conditional operator is ill-formed. Please check the rules for return type of the conditional operator.
In this case, just use a normal conditional:
if (i)
std::cout << "First i = " << i << std::endl;
else
i = 10;
Let's say we have function g:
int g(int x, int& y)
{
y = y + x++;
return x + y;
}
And main function:
int main()
{
int x = 5;
int y = 2;
cout << g(g(x, y), y) << ' ';
cout << x << ' ' << y << endl;
}
It prints expected result:
34 5 20
But when I rewrote main:
int main()
{
int x = 5;
int y = 2;
cout << g(g(x, y), y) << ' ' << x << ' ' << y << endl;
}
It prints
34 5 2
Can someone please explain me why we have different behavior in these two situations ?
Prior to C++17, in the line:
cout << g(g(x, y), y) << ' ' << x << ' ' << y << endl;
the value stored in x and y for the latter part of the expression could each either be read before or after or in between the calls to g.
Note that the expressions y in the argument list for g do not read the stored value: y is an lvalue being bound directly to an lvalue reference function parameter, so there is no lvalue-to-rvalue conversion.
The calls to g have the following behaviour, where x and y refer to the variables in main:
Initial: x = 5, y = 2.
After inner call to g: x = 5, y = 7 (call returns 13).
After outer call to g: x = 5, y = 20 (call returns 34).
So the output will start with 34 5, but the last number could either be 2, 7 or 20. This is known as unspecified behaviour.
Since C++17, the operands of a << chain are sequenced from left to right; the only possible output now is 34 5 20.
Note: Some comments claimed there is undefined behaviour, however there is not. In C++03 terminology, there is a sequence point on entry and exit of a function call; the modification of y in the function is separated from the read of y in main by one of those sequence points. In C++11 the sequencing is the same but the terminology changed. See point 11 here.
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);
I use the stream operator << and the bit shifting operator << in one line.
I am a bit confused, why does code A) not produce the same output than code B)?
A)
int i = 4;
std::cout << i << " " << (i << 1) << std::endl; //4 8
B)
myint m = 4;
std::cout << m << " " << (m << 1) << std::endl; //8 8
class myint:
class myint {
int i;
public:
myint(int ii) {
i = ii;
}
inline myint operator <<(int n){
i = i << n;
return *this;
}
inline operator int(){
return i;
}
};
thanks in advance
Oops
Your second example is undefined behavior.
You have defined the << operator on your myint class as if it were actually <<=. When you execute i << 1, the value in i is not modified, but when you execute m << 1, the value in m is modified.
In C++, it is undefined behavior to both read and write (or write more than once) to a variable without an intervening sequence point, which function calls and operators are not, with respect to their arguments. It is nondeterministic whether the code
std::cout << m << " " << (m << 1) << std::endl;
will output the first m before or after m is updated by m << 1. In fact, your code may do something totally bizarre, or crash. Undefined behavior can lead to literally anything, so avoid it.
One of the proper ways to define the << operator for myint is:
myint operator<< (int n) const
{
return myint(this->i << n);
}
(the this-> is not strictly necessary, just my style when I overload operators)
Because int << X returns a new int. myint << X modifies the current myint. Your myint << operator should be fixed to do the former.
The reason you're getting 8 for the first is that apparently m << 1 is called first in your implementation. The implementation is free to do them in any order.
Your << operator is in fact a <<= operator. If you replace the line with
std::cout << i << " " << (i <<= 1) << std::endl; //8 8
you should get 8 8.
since m is a myInt your second example could be rewritten as:
std::cout << m << " " << (m.operator<<( 1)) << std::endl;
The order of evaluation for the subexpressions m and (m.operator<<( 1)) is unspecified, so there's no saying which "m" you'll get for the 1'st expression that m is used in (which is a simple m expression). So you might get a result of "4 8" or you might get "8 8".
Note that the statement doesn't result in undefined behavior because there are sequence points (at least one function call) between when m is modified and when it's 'read'. But the order of evaluation of the subexpressions is unspecified, so while the compiler has to produce a result (it can't crash - at least not legitimately), there's no saying which of the two possible results it should produce.
So the statement is about as useful as one that has undefined behavior, which is to say it's not very useful.
Well (m << 1) is evaluated before m and therefore m holds 8 already, as in your operator<< you overwrite your own value.
This is wrong behaviour on your side, the operator<< should be const and not change your object.
Because the << operator of myint modifies its lhs. So after evaluating m << 1, m will actually have the value 8 (while i << 1 only returns 8, but does not make i equal to 8). Since it is not specified whether m<<1 executes before cout << m (because it's not specified in which order the arguments of a function or operator are evaluated), it is not specified whether the output will be 8 8 or 4 8.
The C++ language does not define the order of evaluation of operators. It only defines their associativity.
Since your results depend on when the operator<< function is evaluated within the expression, the results are undefined.
Algebraic operator $ functions should always be const and return a new object:
inline myint operator <<(int n) const { // ensure that "this" doesn't change
return i << n; // implicit conversion: call myint::myint(int)
}