I mean
double x=5;
double k=Func(x+3.5,h+1.2);//I send x=8.5
double y=x;//x=5;
I want to change it when I send it.
double x=5;
double k=Func(x+3.5,h+1.2);
double y=x;//x=8.5
Is it possible to do?
Please don't do this. Yes. That's my answer.
It is, however, possible because assignment statements with side-effects by definition can be used as expressions. I have removed the extra code that didn't seem to apply.
void Func (double _x) {
// do nothing
// _x = 8.5 when invoked from below
}
double x = 5;
Func(x = x + 3.5); // or Func(x += 3.5)
// x = 8.5
The above is [almost always] much better written with the assignment -- and thus side-effect -- kept separately from the function call itself: (In most cases, both forms have identical semantics.)
x += 3.5;
Func(x);
Happy coding.
If you do wish to use out/ref, keep in mind that it only makes sense to use variables as the out/ref parameters: the expression x + 3.5 is not a variable -- it cannot be assigned to -- and is thus unsuitable. (I believe VB.NET also allows properties.)
void Add(ref double _y, double s) {
// _y = 5
_y += s;
// _y = 8.5
}
double y = 5;
Add(ref y, 3.5);
// y = 8.5
Maybe something like this:
double x=5;
double k=Func(x+=3.5,h+1.2);
double y=x;//x should be 8.5
This way x evaluates to 8.5 before the function is called.
But, may I ask why the need to do this?
Your problem is that you are passing the x variable by copy not by reference. This is why x is still 5 after your functions finishes. You should change your function h from:
h(int x, int y)
to
h(int * x, int *y)
EDIT :
With pointers you pass the variable x and do all your operations on it. With no pointers, the function creates a copy of the variable x and works on it then destroys it when the functions ends. So the real x is not modified.
Pointers and references work together. You declare the function with pointers and pass the variables with reference
Related
Today, I'm trying to launch my CUDA C/C++ program from a C# application.
So, I did some research on the web, but I didn't found that much information. I only saw the "GitHub" but, no...
So I've got a Kernel defined like follow :
(that's an example)
__global__ void kernel(Cartesian a, Cartesian b, Cartesian *c)
With "Cartesian" :
class Cartesian
{
public:
double x;
double y;
double z;
};
With what I understand from managedCUDA. It's like replacing the main function of a CUDA C/C++ program. Using a lib that "do the work for us"
So i followed an example from this page :
https://algoslaves.wordpress.com/2013/08/25/nvidia-cuda-hello-world-in-managed-c-and-f-with-use-of-managedcuda/
And write my C# program like this :
The part that create the context : (dont really get this "notion")
static void InitKernels()
{
CudaContext cntxt = new CudaContext();
CUmodule cumodule = cntxt.LoadModule(#"C:\Users\stage\Documents\Visual Studio 2013\Projects\Cs_link_test\Cs_link_test\x64\Release\kernel.ptx");
addWithCuda = new CudaKernel("kernel", cumodule, cntxt);
}
The part that launch (I guess) the function and get back the modification made by the kernel :
static Func<Cartesian, Cartesian, Cartesian> cudaAdd = (a, b) =>
{
CudaDeviceVariable<Cartesian> result_dev;
Cartesian result_host;
addWithCuda.Run(a, b, result_dev.DevicePointer);
result_dev.CopyToHost(ref result_host);
return result_host;
};
And from this part I don't understand anything from the line :
static Func<Cartesian, Cartesian, Cartesian> cudaAdd = (a, b) =>
I'm not familiar with C# (just saying)
So my problem come from the error caused by result_dev and result_host;
The error says :
Use of unassigned local variable 'result_*'
So, is it because they arren't initialized ?
If so, why result_host cause an error ? It must get the data from result_dev which must be modified by the kernel..
If not, how to fix this ?
And I also wanted to know, is it possible to passe Class parameter through a kernel function ? If so, how to set a CudaDeviceVariable, cause it says that the type must be non-nullable. It's why I change class with struct.
Ok so.. I just figured out how to solve my problem. Read the "discussion" section on https://managedcuda.codeplex.com/discussions/659183 help me to do it. So how to proceed to pass struct parameter to a kernel using managedCUDA ?
First thing I did wrong (I guess) is to use the Func<T, T, T>part.
You must declare your class in your .cu file like follow :
class Cartesian
{
public:
double x;
double y;
double z;
}
And the same in your .cs file like follow :
[StructLayout(LayoutKind.Sequential)]
struct Cartesian
{
public double x;
public double y;
public double z;
public Cartesian(double x, double y, double z) { this.x = x; this.y = y; this.z = z; }
};
Then you can initialize your kernel as you want, I do it like this :
static void InitKernels()
{
CudaContext ctx = new CudaContext();
CUmodule cumodule = ctx.LoadModule(#"C:\Users\stage\Documents\Visual Studio 2013\Projects\Cs_link_test\Cs_link_test\x64\Release\kernel.ptx");
kernel = new CudaKernel("kernelPosGeo", cumodule, ctx);
kernel.BlockDimensions = 1024;
kernel.GridDimensions = 614;
}
And what you need to do is simply call your kernel with the parameters you want.
Cartesian a = new Cartesian(1, 2, 3);
kernel.Run(a);
I guess I had a problem because I used Func<T, T,T> but till I don't use it anymore, it seems easier. And the declaration of Func had at maximum 2 parameter in and 1 out. So I've got a Kernel that have 4 or 5 parameters and I was limited here... But right now, do not have any problem.
While I realize I'm not being very rigorous, I'm pretty sure the definition of a combinator in simple terms is simply a function with no free variables. For example,
f(x,y) = x + y
would be a combinator and
f(x,y) = x * 2
would not be because y would be free.
So given that understanding would a member variable in a class definition be considered "free"? I'm guessing it would but I wanted to check my assumption. Code like this C# example:
namespace ConsoleApplication1
{
class BoundOrFree
{
private int _i = 0;
public int f(int x, int y)
{
return x + y + _i;
}
}
}
In the BoundOrFree.f member function is _i free? Would f therefore not be a combinator? I'm assuming the answer to both of those questions would be yes but I wanted to confirm my assumption.
would not be because y would be free
you misinterpret the "free" term in this case. Free variable is the one that was captured from the outer scope (via a closure). So f(x,y) = x * 2 is a combinator.
Answering your question
In the BoundOrFree.f member function is _i free? Would f therefore not be a combinator?
the BoundOrFree::f function is not a combinator, since it uses variables other than its only arguments.
can anyone suggest me the exact use of out keyword as a paramter, and how its connected for returning multiple values from the function, as in this POST, i am confused with out variable with normal variable. can anyone help me for this.
This is frequently confusing, and I think the MSDN documentation actually is a bit "clear only if already known". That is, it is correct, but it really only makes sense if you already understand the concept.
Here's how I think of it.
A regular parameter makes a copy of the value of the argument. When you say:
static int M(int z) { z = z + 1; return z; }
...
int x = 123;
int y = M(x);
That is just like you said:
int x = 123;
int z = x; // make a copy of x
z = z + 1;
int y = z;
A ref or out parameter make an alias for an existing variable. When you say
static void N(ref int q) { q = q + 1; }
...
int x = 123;
N(x);
That is the same as saying:
int x = 123;
// MAGIC: q is now an another name for variable x
q = q + 1;
q and x are two different names that refer to the same variable. Incrementing q also increments x because they are the same. z and x in the previous example are two different names that refer to two different variables. Incrementing z does not change x.
Summing up: "out" and "ref" just mean "do not make a new variable; rather, temporarily make a second name for an existing variable".
Is that now clear?
UPDATE: I did not say what the difference between "out" and "ref" is. The difference is simple. On the "caller" side, a "ref" must be a definitely assigned variable before the method is called. An "out" need not be. On the "callee" side, a "ref" may be read before it is written to, but an "out" must be written to before it is read. Also, an "out" must be written to before control leaves the method normally.
MSDN documentation already does a great job explaining this:
The out keyword causes arguments to be passed by reference. This is
similar to the ref keyword, except that ref requires that the variable
be initialized before being passed. To use an out parameter, both the
method definition and the calling method must explicitly use the out
keyword. For example:
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
It's very frequently used in a pattern that "tries" to get a value, something like:
int result;
if(Int32.TryParse("123", out result))
{
Console.WriteLine(result + 1);
}
out keyword should be used when you want to:
a) Allow your function to modify specific variable from calling code stack AND
b) enforce setting this variable value inside your function
MSDN is always a good place to start
In most languages c# included you can pass values in 2 ways, by value, by reference.
by value gives the method a copy of your data, so changing the data wont have any effect on the original data
by reference essentially gives the method the memory address of your data, so if the method modifies the data, it changes the original.
Out is a special type of ref, in that you do not need to initialise the variable before you call the method, it can be called with null being passed in. and it MUST be set by the method.
Another way you can think of it (from the outside code's point of view) is:
val = read only
ref = read/write
out = write only.
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx
out keyword is good if you want to return multiple values of pre-defined types (for example an int, a List<string> and a DateTime), and you don't want to create a new class just for this purpose.
Ok,
let look at the usual pattern for this kind of function - the TrySomething.
Suppose you have a function that might succeed giving you an value or not but you don't won't to use an exception for this because you don't want the overhead or it's a common trait.
Then you normaly return true if the method suceeded and false if not. But where would you put your outputvalue to?
One possible answer is using an out parameter like this:
bool TrySomething(MyInputType input, out MyOutputType output)
{
output = default(MyOutputType);
/* ... Try getting the answer ... */
if (!successful)
return false;
output = successfulOutput;
return true;
}
Remark:
Or you might consider using a Tuple<bool,MyOutputType> and indeed F# interpretes the pattern above as resulting in such a tuple by itself.
Reading C# In Depth, 2nd edition, section 2.1.2 on combining and removing delegates.
The subsection title states that "delegates are immutable" and that "nothing about them can be changed." In the next paragraph, though, it talks about using constructs like
x += y;
where x and y are variables of compatible delegate types.
Didn't I just change x? Or does the immutability part deal with when x is disposed of when I do this (i.e., immediately)?
That's like doing:
string x = "x";
string y = "y";
x += y;
Strings are immutable too. The code above not changing the string objects - it's setting x to a different value.
You need to differentiate between variables and objects. If a type is immutable, that means that you can't change the data within an instance of that type after it's been constructed. You can give a variable of that type a different value though.
If you understand how that works with strings, exactly the same thing is true with delegates. The += actually called Delegate.Combine, so this:
x += y;
is equivalent to:
x = Delegate.Combine(x, y);
It doesn't change anything about the delegate object that x previously referred to - it just creates a new delegate object and assigns x a value which refers to that new delegate.
You have changed x, but didn't change its value (i.e. the delegate it was holding).
It's the same as:
int num = 4;
num += 2;
These operands may be simple but the difficulty of finding explanations which are definitive and complete prompted me to ask. What are the character combinations containing an operand followed by an equal sign (such as *=, -=,+=, etc), what do they do and how are they useful (especially pertaining to non-numeric fields)?
Examples as well as definitions would be greatly appreciated.
Thanks
They are usually interpreted broadly as:
x += y === x = x + y
(etc for your choice of operator)
however; some languages allow you to have a bespoke += operator*, or may interpret it differently in some scenarios; for example, in C# events, += and -= mean "subscribe via the add accessor" and "unsubscribe via the remove accessor" respectively.
Typically they are just space savers, but there can be semantic differences in some cases.
*=where I mean: very different to just the + operator and assignment
Pretty much all the answers here state that x += y; is "equivalent" to "x = x + y;".
This is not actually true. They are not exactly equivalent for several reasons.
First, side effects are only performed once. Suppose you have
class C { public string S { get; set; } }
class D
{
private static C c = new C();
static C M()
{
Console.WriteLine("hello!");
return c;
}
}
The first line below prints "hello" once, as you would expect. The second prints it twice.
D.M().S += "abc";
D.M().S = D.M().S + "abc";
Second, the type system works differently for compound assignment than for regular assignment.
short b = 1;
short c = 2;
b += c;
b = b + c;
The third line is legal. The fourth line is not; a short plus a short is an int in C#, so b = b + c is an illegal assigning of an int to a short. In this case the compound assignment is actually equivalent to b = (short)(b + c);
If this subject interests you I encourage you to read sections 7.17.2 and 7.17.3 of the C# specification.
The great advantage is that you can say:
x += y;
Instead of the more verbose:
x = x + y;
Sometimes this is nice when working with strings, as you can use += to append text to an existing string.
x += expression is roughly the same thing as x = x + (expression). In other words, it calculates the right-hand side, then applies the + operator to the left-hand side and the result, and then assigns that result back into the left-hand side.
Personally, I'm not a huge fan of them. The /= operator I find a particular menace, as there are many Pascal-related languages that use that to indicate boolean inequality. Someone familiar with that who gets mixed up and tries to use it in C ends up with compiling code that produces some of the most bizzare bugs imagineable.
However, they do come in quite handy when the left-hand side is kind of large, so repeating it would throw out more noise than enlightenment.
These are compound assignment operators. For numeric fields, they're defined to add (+=), multiply (*=), and subtract (-=) the value on the right- from the variable on the left, and assign the result to the variable on the left.
However, C++ supports "operator overloading". Meaning, for any given object, the programmer can define what happens if you write x += 12 and x happens to be an object of type Foo rather than an int. This is commonly done for string classes, so if s1 = "All this" you can write s1 += " and more" and the result will be "All this and more".
Say you have x = 5. If you want to add 1 to x, you can do it in many ways:
x = x + 1;
x += 1;
x++;
++x;
They're all equivalent, and choosing any of those should leave x with 6.
So basically, if you want to multiply, divide, or subtract from x, just change the + operator to what you want.
Sorry, I didn't see that you mentioned non-numeric fields. In C# and in C++, you can do something called an "operator overload" to give a non-numeric object the ability to utilize these compound operators with a user-defined function and/or comparison.
For instance, strings are generally treated as objects and not as primitive data types, but if you execute String s = "hello"; s += "!";, you'll see that s will contain hello!. That's because the String object has an overloaded operator for += that applies an append with the rvalue ("!"--right of the += operator) to the lvalue ("hello"--left of the += operator).
A related question on C# operator overloading:
Simple way to overload compound assignment operator in C#?
If you want an explanation try reading http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound-assignment_operators like someone already suggested, basically a += b; is equivalent to a = a + b;. It's shorthand to make your code easier to write and read.
Here are some examples:
/* Print all evens from 0 through 20 */
for(i = 0; i <= 20; i += 2){
printf("%d\n", i);
}
/* Slow down at a linear pace */
/* Stop after speed is 0.1 or less */
while(speed > 0.1){
speed /= 1.2;
}
speed = 0;
Those should explain it. It applies to bitwise operations as well as arithmetic, but I can't think of any simple uses off the top of my head and I don't want to confuse you. There's the old temp-less swap trick - a ^= b ^= a ^= b; - which will swap the values of a and b without you having to create a temporary variable, but I'm not sure if you know what the bitwise XOR operation is at this point, so don't read into it yet.
With regard to non-numeric fields: what the operators do is completely arbitrary. In C/++/#, you can override what an operator does, allowing you to write something like:
MyObj += MyOtherObj;
// MyObj is now null
When overloading the operators, you can really do whatever you like.