C# unassigned variable? - c#

I am new to C# programming, and I don't know very much of its syntax or how it works, but I've been learning and it's been coming along quite nicely. I'm trying to convert one of my programs I have recently written in Python to C# so it can run on windows without having to install Python. And I've had to change a lot of my methods in converting it, and it's taken a very long time to do, but I've been figuring most things out as I go along. This issue, however, makes absolutely no sense to me. I have assigned a value and a type to the double 'b1' but it's telling me that I can't use it in the definition of b2?
double b;
double b1;
double b2;
if (noSlope == true)
b = 0;
else
b1 = slopem * Convert.ToDouble(x1);
b2 = Convert.ToDouble(y1) - b1;
b = b2;
Visual Studio has been telling me that 'b1' is an unassigned local variable. I thought I just assigned it on the line above? Can anyone tell me why it is doing this, or how to assign a value to b1 so it can be used? Thanks in advance!

In c# blocks are marked using { and }, not indentation. Your current code is equivalent to
double b;
double b1;
double b2;
if (noSlope == true)
{
b = 0;
}
else
{
b1 = slopem * Convert.ToDouble(x1);
}
b2 = Convert.ToDouble(y1) - b1;
b = b2;
As you can see, when the condition is evaluated to true you will not have b1 assigned.
PS. You can rewrite your code to
double b;
if (noSlope == true)
{
b = 0;
}
else
{
b = Convert.ToDouble(y1) - slopem * Convert.ToDouble(x1);
}
or even
double b = noSlope ? 0 : Convert.ToDouble(y1) - slopem * Convert.ToDouble(x1);

Related

Swap two numbers without using another variable [duplicate]

This question already has answers here:
Swap two variables without using a temporary variable
(29 answers)
Closed 8 years ago.
Swap two variables without using a temp variable
if
int a=4;
int b=3;
I need to swap these variable and get output as
a=3 and b=4
without using another variable in C#
Use Interlocked.Exchange()
int a = 4;
int b = 3;
b = Interlocked.Exchange(ref a, b);
Tell me more
From MSDN:
Sets a 32-bit signed integer to a specified value as an atomic operation, and then returns the original value
EDIT: Regarding Esoteric's fine link above (thank-you), there's even a Interlocked.Exchange() for double that may help there too.
use the following concept
int a=4 ;
int b=3 ;
a=a+b ; // a=7
b=a-b ; // b=7-3=4
a=a-b ; // c=7-4=3
There are actually a couple of ways.
The following is considered an obfuscated swap.
a ^= b;
b ^= a;
a ^= b;
a = a + b;
b = a - b;
a = a - b;
Works the same with any language.
Using addition and subtraction
a = a + b;
b = a - b;
a = a - b;
Using xor operator
a = a ^ b;
b = a ^ b;
a = a ^ b;
http://chris-taylor.github.io/blog/2013/02/25/xor-trick/

Value not getting right answer

int c;
int f = 20;
c = 5 / 9 * (f - 32);
Console.WriteLine(c);
Console.ReadLine();
If I run this code c ends up being 0, which is wrong. Can anyone tell me why?
Because your calculation is being done in integer type. I believe c is double type variable.
c = 5d / 9 * (f - 32.0);
use 32.0 or 32d so that one of the operands is double, also do the same for 5/9.
Also you need to define c as double.
the problem is in the following line;
5 / 9
because c and f are integers.
For instance, if I asked you to divide 11 to 10; you will tell me the result is 1.1. Assume that you do not know about floating point arithmetic, then you will say either it is not possible to divide 11 to 10; or you will say it is 1. Runtime environment does the same, it says it is 0 since you are declaring an integer.
Habib already explained what is happening. Here is what you could do if you don't want to change c to a float or double:
c = (int)Math.Round(5.0 / 9.0 * (f - 32.0));

C# Calculator , how to point an Input to the answer?

I am making a calculator on C#.
I have to use float because, when I divide numbers, I get an answer less than 0.
but, I want the calculator to begin the new calculation with the answer i already got, So i wrote:
a = Convert.ToInt64(answer);
but, it doesn't help, it converts the answer to int64 too.
I think, I will be able to do with pointers, but I don't know how.
So how can I copy the value of answer to 'a' (the Input), without converting answer?
Int64 a; //1st Input
Int64 b; //2nd Input
float answer;
char d;
bool pressed;
private void button11_Click(object sender, EventArgs e)
{
if (d == '+') answer = a + b;
if (d == '-') answer = a - b;
if (d == '*') answer = a * b;
if (d == '/') answer = a / b;
textBox1.Text = a.ToString() + d + b.ToString() + '=' +answer.ToString();
a = Convert.ToInt64(answer);
b = 0;
}
sorry, for the lack of the whole source code, if anybody want's me to add them too just tell me :)
Couple of observations that may help:
Your inputs probably shouldn't be Int64 in the first place, as it is unlikely the user will work only in whole numbers, especially once they start using division.
Your answer and your inputs should be the same type, this will remove your casting issues.
Float is imprecise and may not be the best option. If you need better accuracy than Float can allow, you may try Decimal. (if you are unaware of the limitations of floating point arithmetic, Google for it)
First off guys, he's not asking how to make a calculator, he's just asking for help on a specific problem, I think that's what SO is supposed to be about.
You are on the right track, just needs some adjustments.
Operations
You most likely don't need Int64, you are probably looking for float or double. So here is a simple example:
float a = 1.0f;
float b = 2.0f;
float answer = a / b;
Here the answer would be 0.5, if a and b were integers the answer would be 0. If either one (or both) are float or double then the answer will be a decimal number.
If Statement
While we are at it, your if statement can be improved by making it an if-else:
if (d == '+') answer = a + b;
else if (d == '-') answer = a - b;
else if (d == '*') answer = a * b;
else if (d == '/') answer = a / b;
Why? Because d is only going to be one of those strings (+, -, *, /). With if-else, once a case is true the rest of the if's are skipped. With your code, even if d is +, the other three if statements are still checked.
Two options to consider:
Do only integer division.
Use floating point variable types for both input and output.

Help with optimizing C# function via C and/or Assembly

I have this C# method which I'm trying to optimize:
// assume arrays are same dimensions
private void DoSomething(int[] bigArray1, int[] bigArray2)
{
int data1;
byte A1, B1, C1, D1;
int data2;
byte A2, B2, C2, D2;
for (int i = 0; i < bigArray1.Length; i++)
{
data1 = bigArray1[i];
data2 = bigArray2[i];
A1 = (byte)(data1 >> 0);
B1 = (byte)(data1 >> 8);
C1 = (byte)(data1 >> 16);
D1 = (byte)(data1 >> 24);
A2 = (byte)(data2 >> 0);
B2 = (byte)(data2 >> 8);
C2 = (byte)(data2 >> 16);
D2 = (byte)(data2 >> 24);
A1 = A1 > A2 ? A1 : A2;
B1 = B1 > B2 ? B1 : B2;
C1 = C1 > C2 ? C1 : C2;
D1 = D1 > D2 ? D1 : D2;
bigArray1[i] = (A1 << 0) | (B1 << 8) | (C1 << 16) | (D1 << 24);
}
}
The function basically compares two int arrays. For each pair of matching elements, the method compares each individual byte value and takes the larger of the two. The element in the first array is then assigned a new int value constructed from the 4 largest byte values (irrespective of source).
I think I have optimized this method as much as possible in C# (probably I haven't, of course - suggestions on that score are welcome as well). My question is, is it worth it for me to move this method to an unmanaged C DLL? Would the resulting method execute faster (and how much faster), taking into account the overhead of marshalling my managed int arrays so they can be passed to the method?
If doing this would get me, say, a 10% speed improvement, then it would not be worth my time for sure. If it was 2 or 3 times faster, then I would probably have to do it.
Note: please, no "premature optimization" comments, thanks in advance. This is simply "optimization".
Update: I realized that my code sample didn't capture everything I'm trying to do in this function, so here is an updated version:
private void DoSomethingElse(int[] dest, int[] src, double pos,
double srcMultiplier)
{
int rdr;
byte destA, destB, destC, destD;
double rem = pos - Math.Floor(pos);
double recipRem = 1.0 - rem;
byte srcA1, srcA2, srcB1, srcB2, srcC1, srcC2, srcD1, srcD2;
for (int i = 0; i < src.Length; i++)
{
// get destination values
rdr = dest[(int)pos + i];
destA = (byte)(rdr >> 0);
destB = (byte)(rdr >> 8);
destC = (byte)(rdr >> 16);
destD = (byte)(rdr >> 24);
// get bracketing source values
rdr = src[i];
srcA1 = (byte)(rdr >> 0);
srcB1 = (byte)(rdr >> 8);
srcC1 = (byte)(rdr >> 16);
srcD1 = (byte)(rdr >> 24);
rdr = src[i + 1];
srcA2 = (byte)(rdr >> 0);
srcB2 = (byte)(rdr >> 8);
srcC2 = (byte)(rdr >> 16);
srcD2 = (byte)(rdr >> 24);
// interpolate (simple linear) and multiply
srcA1 = (byte)(((double)srcA1 * recipRem) +
((double)srcA2 * rem) * srcMultiplier);
srcB1 = (byte)(((double)srcB1 * recipRem) +
((double)srcB2 * rem) * srcMultiplier);
srcC1 = (byte)(((double)srcC1 * recipRem) +
((double)srcC2 * rem) * srcMultiplier);
srcD1 = (byte)(((double)srcD1 * recipRem) +
((double)srcD2 * rem) * srcMultiplier);
// bytewise best-of
destA = srcA1 > destA ? srcA1 : destA;
destB = srcB1 > destB ? srcB1 : destB;
destC = srcC1 > destC ? srcC1 : destC;
destD = srcD1 > destD ? srcD1 : destD;
// convert bytes back to int
dest[i] = (destA << 0) | (destB << 8) |
(destC << 16) | (destD << 24);
}
}
Essentially this does the same thing as the first method, except in this one the second array (src) is always smaller than the first (dest), and the second array is positioned fractionally relative to the first (meaning that instead of being position at, say, 10 relative to dest, it can be positioned at 10.682791).
To achieve this, I have to interpolate between two bracketing values in the source (say, 10 and 11 in the above example, for the first element) and then compare the interpolated bytes with the destination bytes.
I suspect here that the multiplication involved in this function is substantially more costly than the byte comparisons, so that part may be a red herring (sorry). Also, even if the comparisons are still somewhat expensive relative to the multiplications, I still have the problem that this system can actually be multi-dimensional, meaning that instead of comparing 1-dimensional arrays, the arrays could be 2-, 5- or whatever-dimensional, so that eventually the time taken to calculate interpolated values would dwarf the time taken by the final bytewise comparison of 4 bytes (I'm assuming that's the case).
How expensive is the multiplication here relative to the bit-shifting, and is this the kind of operation that could be sped up by being offloaded to a C DLL (or even an assembly DLL, although I'd have to hire somebody to create that for me)?
Yes, the _mm_max_epu8() intrinsic does what you want. Chews through 16 bytes at a time. The pain-point is the arrays. SSE2 instructions require their arguments to be aligned at 16-byte addresses. You cannot get that out of the garbage collected heap, it only promises 4-byte alignment. Even if you trick it by calculating an offset in the array that's 16-byte aligned then you'll lose when the garbage collector kicks in and moves the array.
You'll have to declare the arrays in the C/C++ code, using the __declspec(align(#)) declarator. Now you need to copy your managed arrays into those unmanaged ones. And the results back. Whether you are still ahead depends on details not easily seen in your question.
The function below uses unsafe code to treat the integer arrays as arrays of bytes so that there's no need for bit twiddling.
private static void DoOtherThing(int[] bigArray1, int[] bigArray2)
{
unsafe
{
fixed (int* p1 = bigArray1, p2=bigArray2)
{
byte* b1 = (byte*)p1;
byte* b2 = (byte*)p2;
byte* bend = (byte*)(&p1[bigArray1.Length]);
while (b1 < bend)
{
if (*b1 < *b2)
{
*b1 = *b2;
}
++b1;
++b2;
}
}
}
}
On my machine running under the debugger in Release mode against arrays of 25 million ints, this code is about 29% faster than your original. However, running standalone, there is almost no difference in runtime. Sometimes your original code is faster, and sometimes the new code is faster.
Approximate numbers:
Debugger Standalone
Original 1,400 ms 700 ms
My code 975 ms 700 ms
And, yes, I did compare the results to ensure that the functions do the same thing.
I'm at a loss to explain why my code isn't faster, since it's doing significantly less work.
Given these results, I doubt that you could improve things by going to native code. As you say, the overhead of marshaling the arrays would likely eat up any savings you might realize in the processing.
The following modification to your original code, though, is 10% to 20% faster.
private static void DoSomething(int[] bigArray1, int[] bigArray2)
{
for (int i = 0; i < bigArray1.Length; i++)
{
var data1 = (uint)bigArray1[i];
var data2 = (uint)bigArray2[i];
var A1 = data1 & 0xff;
var B1 = data1 & 0xff00;
var C1 = data1 & 0xff0000;
var D1 = data1 & 0xff000000;
var A2 = data2 & 0xff;
var B2 = data2 & 0xff00;
var C2 = data2 & 0xff0000;
var D2 = data2 & 0xff000000;
if (A2 > A1) A1 = A2;
if (B2 > B1) B1 = B2;
if (C2 > C1) C1 = C2;
if (D2 > D1) D1 = D2;
bigArray1[i] = (int)(A1 | B1 | C1 | D1);
}
}
What about this?
private void DoSomething(int[] bigArray1, int[] bigArray2)
{
for (int i = 0; i < bigArray1.Length; i++)
{
var data1 = (uint)bigArray1[i];
var data2 = (uint)bigArray2[i];
bigArray1[i] = (int)(
Math.Max(data1 & 0x000000FF, data2 & 0x000000FF) |
Math.Max(data1 & 0x0000FF00, data2 & 0x0000FF00) |
Math.Max(data1 & 0x00FF0000, data2 & 0x00FF0000) |
Math.Max(data1 & 0xFF000000, data2 & 0xFF000000));
}
}
It has a lot less bit shifting in it. You might find the calls to Math.Max aren't inlined if you profile it. In such a case, you'd just make the method more verbose.
I haven't tested this code as I don't have an IDE with me. I reckon it does what you want though.
If this still doesn't perform as you'd expect, you could try using pointer arithmetic in an unsafe block, but I seriously doubt that you'd see a gain. Code like this is unlikely to be faster if you extern to it, from everything I've read. But don't take my word for it. Measure, measure, measure.
Good luck.
I don't see any way of speeding up this code by means of clever bit tricks.
If you really want this code to be faster, the only way of significantly (>2x or so) speeding it up on x86 platform I see is to go for assembler/intrinsics implementation. SSE has the instruction PCMPGTB that
"Performs a SIMD compare for the greater value of the packed bytes, words, or doublewords in the destination operand (first operand) and the source operand (second operand). If a data element in the destination operand is greater than the corresponding date element in the source operand, the corresponding data element in the destination operand is set to all 1s; otherwise, it is set to all 0s."
XMM register would fit four 32-bit ints, and you could loop over your arrays reading the values, getting the mask and then ANDing the first input with the mask and the second one with inverted mask.
On the other hand, maybe you can reformulate your algorithm so that you don't need to to pick larger bytes, but maybe for example take AND of the operands? Just a thought, hard to see if it can work without seeing the actual algorithm.
Another option for you is, if you're able to run Mono, is to use the Mono.Simd package. This provides access into SIMD instruction set from within .NET. Unfortunately you can't just take the assembly and run it on MS's CLR, as the Mono runtime treats is in a special way at JIT time. The actual assembly contains regular IL (non-SIMD) 'simulations' of the SIMD operations as a fall-back, in case the hardware does not support SIMD instructions.
You also need to be able to express your problem using the types that the API consumes, as far as I can make out.
Here is the blog post in which Miguel de Icaza announced the capability back in November 2008. Pretty cool stuff. Hopefully it will be added to the ECMA standard and MS can add it to their CLR.
You might like to look at the BitConverter class - can't remember if it is the right endianness for the particular conversion you're trying to do, but worth knowing about anyway.

Swap two variables without using a temporary variable

I'd like to be able to swap two variables without the use of a temporary variable in C#. Can this be done?
decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);
// Swap each:
// startAngle becomes: 355.87
// stopAngle becomes: 159.9
C# 7 introduced tuples which enables swapping two variables without a temporary one:
int a = 10;
int b = 2;
(a, b) = (b, a);
This assigns b to a and a to b.
The right way to swap two variables (at the time this question was asked(1)) is:
decimal tempDecimal = startAngle;
startAngle = stopAngle;
stopAngle = tempDecimal;
In other words, use a temporary variable.
There you have it. No clever tricks, no maintainers of your code cursing you for decades to come, no entries to The Daily WTF, and no spending too much time trying to figure out why you needed it in one operation anyway since, at the lowest level, even the most complicated language feature is a series of simple operations.
Just a very simple, readable, easy to understand, t = a; a = b; b = t; solution.
In my opinion, developers who try to use tricks to, for example, "swap variables without using a temp" or "Duff's device" are just trying to show how clever they are (and failing miserably).
I liken them to those who read highbrow books solely for the purpose of seeming more interesting at parties (as opposed to expanding your horizons).
Solutions where you add and subtract, or the XOR-based ones, are less readable and most likely slower than a simple "temp variable" solution (arithmetic/boolean-ops instead of plain moves at an assembly level).
Do yourself, and others, a service by writing good quality readable code.
That's my rant. Thanks for listening :-)
As an aside, I'm quite aware this doesn't answer your specific question (and I'll apologise for that) but there's plenty of precedent on SO where people have asked how to do something and the correct answer is "Don't do it".
(1) Improvements to the language and/or .NET Core since that time have adopted the "Pythonic" way using tuples. Now you can just do:
(startAngle, stopAngle) = (stopAngle, startAngle);
to swap values.
First of all, swapping without a temporary variable in a language as C# is a very bad idea.
But for the sake of answer, you can use this code:
startAngle = startAngle + stopAngle;
stopAngle = startAngle - stopAngle;
startAngle = startAngle - stopAngle;
Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.
If you want to hide the temporary variable, you can use a utility method:
public static class Foo {
public static void Swap<T> (ref T lhs, ref T rhs) {
T temp = lhs;
lhs = rhs;
rhs = temp;
}
}
Yes, use this code:
stopAngle = Convert.ToDecimal(159.9);
startAngle = Convert.ToDecimal(355.87);
The problem is harder for arbitrary values. :-)
int a = 4, b = 6;
a ^= b ^= a ^= b;
Works for all types including strings and floats.
BenAlabaster showed a practical way of doing a variable switch, but the try-catch clause is not needed. This code is enough.
static void Swap<T>(ref T x, ref T y)
{
T t = y;
y = x;
x = t;
}
The usage is the same as he shown:
float startAngle = 159.9F
float stopAngle = 355.87F
Swap(ref startAngle, ref stopAngle);
You could also use an extension method:
static class SwapExtension
{
public static T Swap<T>(this T x, ref T y)
{
T t = y;
y = x;
return t;
}
}
Use it like this:
float startAngle = 159.9F;
float stopAngle = 355.87F;
startAngle = startAngle.Swap(ref stopAngle);
Both ways uses a temporary variable in the method, but you don't need the temporary variable where you do the swapping.
A binary XOR swap with a detailed example:
XOR truth table:
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
Input:
a = 4;
b = 6;
Step 1: a = a ^ b
a : 0100
b : 0110
a^b: 0010 = 2 = a
Step 2: b = a ^ b
a : 0010
b : 0110
a^b: 0100 = 4 = b
Step 3: a = a ^ b
a : 0010
b : 0100
a^b: 0110 = 6 = a
Output:
a = 6;
b = 4;
In C# 7:
(startAngle, stopAngle) = (stopAngle, startAngle);
Not in C#. In native code you might be able to use the triple-XOR swap trick, but not in a high level type-safe language. (Anyway, I've heard that the XOR trick actually ends up being slower than using a temporary variable in many common CPU architectures.)
You should just use a temporary variable. There's no reason you can't use one; it's not like there's a limited supply.
For the sake of future learners, and humanity, I submit this correction to the currently selected answer.
If you want to avoid using temp variables, there are only two sensible options that take first performance and then readability into consideration.
Use a temp variable in a generic Swap method. (Absolute best performance, next to inline temp variable)
Use Interlocked.Exchange. (5.9 times slower on my machine, but this is your only option if multiple threads will be swapping these variables simultaneously.)
Things you should never do:
Never use floating point arithmetic. (slow, rounding and overflow errors, hard to understand)
Never use non-primitive arithmetic. (slow, overflow errors, hard to understand) Decimal is not a CPU primitive and results in far more code than you realize.
Never use arithmetic period. Or bit hacks. (slow, hard to understand) That's the compiler's job. It can optimize for many different platforms.
Because everyone loves hard numbers, here's a program that compares your options. Run it in release mode from outside Visual Studio so that Swap is inlined. Results on my machine (Windows 7 64-bit i5-3470):
Inline: 00:00:00.7351931
Call: 00:00:00.7483503
Interlocked: 00:00:04.4076651
Code:
class Program
{
static void Swap<T>(ref T obj1, ref T obj2)
{
var temp = obj1;
obj1 = obj2;
obj2 = temp;
}
static void Main(string[] args)
{
var a = new object();
var b = new object();
var s = new Stopwatch();
Swap(ref a, ref b); // JIT the swap method outside the stopwatch
s.Restart();
for (var i = 0; i < 500000000; i++)
{
var temp = a;
a = b;
b = temp;
}
s.Stop();
Console.WriteLine("Inline temp: " + s.Elapsed);
s.Restart();
for (var i = 0; i < 500000000; i++)
{
Swap(ref a, ref b);
}
s.Stop();
Console.WriteLine("Call: " + s.Elapsed);
s.Restart();
for (var i = 0; i < 500000000; i++)
{
b = Interlocked.Exchange(ref a, b);
}
s.Stop();
Console.WriteLine("Interlocked: " + s.Elapsed);
Console.ReadKey();
}
}
<deprecated>
You can do it in 3 lines using basic math - in my example I used multiplication, but simple addition would work also.
float startAngle = 159.9F;
float stopAngle = 355.87F;
startAngle = startAngle * stopAngle;
stopAngle = startAngle / stopAngle;
startAngle = startAngle / stopAngle;
Edit: As noted in the comments, this wouldn't work if y = 0 as it would generate a divide by zero error which I hadn't considered. So the +/- solution alternatively presented would be the best way to go.
</deprecated>
To keep my code immediately comprehensible, I'd be more likely to do something like this. [Always think about the poor guy that's gonna have to maintain your code]:
static bool Swap<T>(ref T x, ref T y)
{
try
{
T t = y;
y = x;
x = t;
return true;
}
catch
{
return false;
}
}
And then you can do it in one line of code:
float startAngle = 159.9F
float stopAngle = 355.87F
Swap<float>(ref startAngle, ref stopAngle);
Or...
MyObject obj1 = new MyObject("object1");
MyObject obj2 = new MyObject("object2");
Swap<MyObject>(ref obj1, ref obj2);
Done like dinner...you can now pass in any type of object and switch them around...
With C# 7, you can use tuple deconstruction to achieve the desired swap in one line, and it's clear what's going on.
decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);
(startAngle, stopAngle) = (stopAngle, startAngle);
For completeness, here is the binary XOR swap:
int x = 42;
int y = 51236;
x ^= y;
y ^= x;
x ^= y;
This works for all atomic objects/references, as it deals directly with the bytes, but may require an unsafe context to work on decimals or, if you're feeling really twisted, pointers. And it may be slower than a temp variable in some circumstances as well.
If you can change from using decimal to double you can use the Interlocked class.
Presumably this will be a good way of swapping variables performance wise. Also slightly more readable than XOR.
var startAngle = 159.9d;
var stopAngle = 355.87d;
stopAngle = Interlocked.Exchange(ref startAngle, stopAngle);
Msdn: Interlocked.Exchange Method (Double, Double)
a = a + b
b = a - b
a = a - b
َ
Beware of your environment!
For example, this doesn’t seem to work in ECMAscript
y ^= x ^= y ^= x;
But this does
x ^= y ^= x; y ^= x;
My advise? Assume as little as possible.
The simple way to swap 2 numbers in just one line:
a=(a+b)-(b=a);
eg: a=1, b=2
Step 1: a=(1+2) - (b=1)
Step 2: a=3-1
=> a=2 and b=1
Efficient way is to use:
C Programming: (x ^= y), (y ^= x), (x ^= y);
Java: x = x ^ y ^ (y = x);
Python: x, y = y, x
Note: Most common mistake people make:
//Swap using bitwise XOR (Wrong Solution in C/C++)
x ^= y ^= x ^= y;
Source: GeeksforGeek
For binary types you can use this funky trick:
a %= b %= a %= b;
As long as a and b are not the exact same variable (e.g. aliases for the same memory) it works.
I hope this might help...
using System;
public class Program
{
public static void Main()
{
int a = 1234;
int b = 4321;
Console.WriteLine("Before: a {0} and b {1}", a, b);
b = b - a;
a = a + b;
b = a - b;
Console.WriteLine("After: a {0} and b {1}", a, b);
}
}
we can do that by doing a simple trick
a = 20;
b = 30;
a = a+b; // add both the number now a has value 50
b = a-b; // here we are extracting one number from the sum by sub
a = a-b; // the number so obtained in above help us to fetch the alternate number from sum
System.out.print("swapped numbers are a = "+ a+"b = "+ b);
Sometimes I wish it were possible to write a function in MSIL inline in C#, similar to how you can write inline assembler in C.
For the record, I once wrote a helper library for C# with various functions for things that were impossible to write in C# but can be written in MSIL (non-zero-based arrays for example). I had this function:
.method public hidebysig static void Swap<T> (
!!T& a,
!!T& b
) cil managed
{
.maxstack 4
ldarg.1 // push a& reference
ldarg.2 // push b& reference
ldobj !!T // pop b&, push b
ldarg.2 // push b& reference
ldarg.1 // push a& reference
ldobj !!T // pop a&, push a
stobj !!T // store a in b&
stobj !!T // store b in a&
ret
}
And no locals needed. Of course this was just me being silly...
startAngle = (startAngle + stopAngle) - (stopAngle = startAngle);
If you want to swap 2 string variables:
a = (a+b).Substring((b=a).Length);
An helper method accordingly:
public static class Foo {
public static void SwapString (ref string a, ref string b) {
a = (a+b).Substring((b=a).Length);
}
}
Usage would be then:
string a="Test 1";
string b="Test 2";
Foo.SwapString(a, b);
Here another approach in one line:
decimal a = 159.9m;
decimal b = 355.87m;
a = b + (b = a) - b;
Here is some different process to swap two variables
//process one
a=b+a;
b=a-b;
a=a-b;
printf("a= %d b= %d",a,b);
//process two
a=5;
b=10;
a=a+b-(b=a);
printf("\na= %d b= %d",a,b);
//process three
a=5;
b=10;
a=a^b;
b=a^b;
a=b^a;
printf("\na= %d b= %d",a,b);
//process four
a=5;
b=10;
a=b-~a-1;
b=a+~b+1;
a=a+~b+1;
printf("\na= %d b= %d",a,b);
this model is very useful
var a = 10;
var b = 20;
(int a,int b) c = (a,b);
a = c.b ;
b = c.a ;
var a = 15;
var b = -214;
a = b | !(b = a);
This works great.
Very simple code for swapping two variables:
static void Main(string[] args)
{
Console.WriteLine("Prof.Owais ahmed");
Console.WriteLine("Swapping two variables");
Console.WriteLine("Enter your first number ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your first number ");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("your vlaue of x is="+x+"\nyour value of y is="+y);
int z = x;
x = y;
y = z;
Console.WriteLine("after Swapping value of x is="+x+"/nyour value of y is="+y);
Console.ReadLine();
}
You can try the following code. It is much more better than the other code.
a = a + b;
b = a - b;
a = a - b;

Categories

Resources