Why does double x = 0,1; not compile? - c++

double x = 0,1;
doesn't compile (tries on on MSVC9.0). The error is
C2059 syntax error : 'constant'
I do realize that there's a comma there instead of a point, but shouldn't the line above be interpreted as the following?
double x = (0,1); //which is double x = 1;
Incidentally, the initialization compiles successfully with the parentheses.
I was thinking along the lines that operator , has a lower precedence than operator =, but in this case = is no operator, so this shouldn't be an issue. What syntactic rules determine that
double x = 0,1;
should be illegal?

Well, it's treated as
double x = 0; double 1;
that's why. Just like you'd write
double x = 0, y;
It's the syntax for a declaration, you're just attempting to declare 1 as a variable (which is wrong). Don't think there's much more to it...

During declarations, the comma in the absence of parenthesis is treated as a separator between declarations. For example:
double x = 0, y = 1;
or
double x = 0, y;
What you typed is the equivalent of
double x = 0;
double 1;
Which is obviously not correct.

Related

lazy-evaluation in Xtensor

In the following function using xtensor, I was expecting the compiler to express the computation graph to auto z = 3.0 * u + 100 * xt::cos(u); and evaluate the result at xt::xtensor_fixed<T, xt::xshape<nn>> out = z; when assigning the expression to an exact tensor.
template<typename T, size_t nn>
T func_cos(xt::xtensor_fixed<T, xt::xshape<nn>> &u) {
auto z = 3.0 * u;
for (auto k = 0; k < 100; ++k){
z += xt::cos(u);
}
xt::xtensor_fixed<T, xt::xshape<nn>> out = z;
return out(0);
}
However, I got an error
views_xtensor.cpp:76:11: error: no viable overloaded '+='
z += xt::cos(u);
[....]
Did I use auto in an wrong way? How could I use lazy evaluation in a for-loop?
Thank you for your help!
When you write
auto z = 3.0 * u
The type of z encodes the operation, it is something like
xfunction<multiplies, scalar<double>, xtensor_fixed>
This class does not hold any value, so it is not possible to assign it anything (even if it is a computed assignment). Now even if iw was possible, consider the following expression
auto y = z + xt::cos(u);
The type of this expression is something like
xfunction<plus, type(z), xfunction<cos, xtensor_fixed>>
So when you write
z += xt::cos(u); // equivalent to z = z + xt::cos(u);
You try to assign z something of a completely different type.
Lazy evaluation cannot be used in for loops for these reasons.

Which is the value of i in this "simple" initialization?

I have a doubt about this code:
int i, x, z = 4, y = 1;
i = x = z += y++;
Which is the value of i? Can we know that value or not?
First of all, have you tested if this compiles at all?
If not, then why?
Unless you write some code that invokes UB, compiler, regarding basic syntax of the language, has most of the answers you'll ever need. Please test it yourself, and if it's still not clear, or behaves weirdly, then it's something worth asking.
In this case, it's valid, so let's go through it.
#include <iostream>
int main() {
int i, x, z = 4, y = 1;
i = x = z += y++;
std::cout << "i=" << i << std::endl;
}
I compiled, ran it, and here's the result:
$ g++ test.cpp -o test
$ ./test
i=5
So, what is actually going on in this line?
i = x = z += y++;
First of all, it's easier to understand when you add parentheses so it's perfectly obvious what is evaluated and when:
i = (x = (z += (y++)));
i is a result of assignment to x;
x is a result of addition assignment to z;
z is a result of z + (y post increment);
You can then work your way backwards through the list, and will arrive at the correct result:
y++ evaluates to simply y, because post increment affects only value of y, not the result of expression itself;
z is then z + y, which is 4 + 1, or 5;
intermediate expression becomes i = x = z; (or, form that's too obvious, i = (x = z);), and that means that i, just like x is 5.
Whatever you do, please don't actually write code like this, while it's easy to deconstruct, it's not something that is easy to understand at a first glance, and that, more often than not, causes confusion.
Can we know that value or not?
Yes.
Which is the value of i?
5
since you add y to i, where their values are 4 (since i gets assigned the value of z, which is 4) and 1 respectively.
y is incremented after z has been initialized. It's incremented in the following statement, as #john commented.
As #LightnessInOrbit commented, this is not good code. Forget about it and move on.
Yes the value of i is 5.
Just trace the code.
y++ post increement i,e first assign the value then increement so Y= 4. Next
z += y shorthand operation i,e.., z= z + y ,initially z=4 so 5 = 4+ 1 so Z=5
x = z i.e, x = 5 Next
i = x i.e, i = 5.

Expression of different type expected

I have the following code:
type point = { x : float; y : float; z : float }
type dpoint = { dx : float; dy : float; dz : float }
type physical_object = { position : point; velocity : dpoint }
let move p dp = {x = p.x + dp.x; y = p.y + dp.y; z = p.z + dp.z}
I am getting this error:
File "code.ml", line 4, characters 21-24:
Error: This expression has type float but an expression was expected of type
int
p.x is highlighted
Why is this?
Am I not referencing the record's fields correctly?
Operator + has type int -> int -> int and thus is applicable only for the values of type int. Use +. operator for floats, (and *., /. correspondingly for other operations).
OCaml doesn't have operator overloading (aka ad hoc polymorphism), as it doesn't play well with type inference. However, it makes your code much more explicit, that can be considered a benefit.
In OCaml, + works on integers only. For floats you have to use the +. operator (that's with a dot suffix). For more details, see e.g. http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html.

Python My programming Lab

I have a problem doing one of the questions from my programming lab.
The question was like "Given the variables x, y, and z, each associated with an int, write a fragment of code that assigns the smallest of these to min."
And my work area looks like
if x < y and x < z:
x = min
if y < x and y < z:
y = min
if z < x and z < y:
z = min
When I turned in, the feedback said:
Remarks:
⇒ Unexpected identifiers: and
More Hints:
⇒ Solutions with your approach don't usually use: <
although I tried may ways to figure it out but none of them worked.
Plz help.
Thx.
For the first reply, the system said:
Remarks:
⇒ Unexpected identifiers: and
More Hints:
⇒ Solutions with your approach don't usually use: <
Problems Detected:
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ Exception occurred(, TypeError('unorderable types: int() < builtin_function_or_method()',), )
⇒ min does not contain the correct value
⇒ y was modified
⇒ z was modified
For the second reply, the system said:
Remarks:
⇒ Unexpected identifiers: and, def, minist
⇒ You have to use the min variable .
⇒ You should use an assignment operator (=) in this exercise.
More Hints:
⇒ You almost certainly should be using: =
⇒ You almost certainly should be using: min
⇒ I haven't yet seen a correct solution that uses: , (comma)
I see three issues with the code as you've shown it in the question.
The first is that your indentation is a bit messed up. You probably want all your if statements to be at the same level, with the corresponding assignment statements indented under each one:
if something:
foo = bar
if something_else:
foo = baz
# etc
You could also use elif statements instead of the second and third if, since you never expect to have more than one of the conditions true at the same time.
The second issue is that you're doing your assignment statements backwards. If you want to assign the value in a variable x to a new variable named min, you should put min on the left side and x on the right:
min = x
This is part of the reason you're getting lots of confusing errors. Before your code runs, min is the name of a builtin function (which I suspect you'll learn about later in your class). When you did x = min you were replacing the old x value with a reference to the function.
The last thing is a logic issue. Your comparisons are all using the < operator to test if one value is smaller than the others. The issue is what happens if two of the values are equal. If x and y have the same value, both x < y and y < x will be False. That's not very good for your code, and so you probably want to use the <= operator instead. It tests if the left side is less than or equal to the right side. With this version, if you're using elifs, you can actually do away with the last condition and just use else, since if neither x or y is less than or equal to the other values, z must be the smallest value by process of elimination.
Anyway, here's the code with all three issues fixed:
if x <= y and x <= z:
min = x
elif y <= x and y <= z:
min = y
else: # no "z <= x and z <= y" check needed here, will always be true if reached
min = z
Maybe the tab problem.
You can try this:
if x < y and x < z:
x = min
if y < x and y < z:
y = min
if z < x and z < y:
z = min
I make a sample:
#-*- coding:utf-8 -*-
def minist(x,y,z):
if x < y and x < z:
return x
if y < x and y < z:
return y
if z < x and z < y:
return z
x = 1
y = 2
z = 3
test = -1
test = minist(x,y,z)
print(test)
This sample will print 1.

Difference between += and =+ in C++

While programming in C++, I often confuse both "+=" and "=+", the former being the operator I actually mean. Visual Studio seems to accept both, yet they behave differently and is a source for a lot of my bugs. I know that a += b is semantically equivalent to a = a+b, but what does "=+" do?
=+ is really = + (assignment and the unary + operators).
In order to help you remember +=, remember that it does addition first, then assignment. Of course that depends on the actual implementation, but it should be for the primitives.
a =+ b means a = +b means a = b
if you see = the first , it means you re-declare your variable value ,
but if you face + the first it means that you order the compiler to increment the value of the variable , keep it in you mind
int x=20 ;
x=+10 ;
cout<< x <<endl ; // x = 10
x+=10 ;
cout<< x<<endl ; // x= 10+10 = 20
I may be remembering this wrong, but I think that in C, C++, and even Java (which has similar syntax to C and C++), =+ and += actually behave very similarly. The statement that =+ is assignment (equivalent to plain = operator), while += increases a variable's value by a certain amount, is INCORRECT.
x += y as well as x =+ y will BOTH have the same effect (that is, both of these will cause the new value of x to be the old value of x + y). The difference comes in when you have a slightly more complex expression.
z = (x += y) and z = (x =+ y) will have DIFFERENT outputs for the variable z.
Let's look at each one of these:
z = (x += y) will add y to x, and then set z to be the NEW value of x.
z = (x =+ y) will set z to be the OLD value of x, and then add y to x.
It's possible I got those 2 backwards, but I do remember reading somewhere before that the differences I describe here are the ACTUAL differences between those 2.