This question already has answers here:
Swapping two variable value without using third variable
(31 answers)
Closed 6 years ago.
we usually use the
a=a+b;
b=a-b;
a=a-b;
logic to solve this code, however, if we work with int, then after say 30000 the code fails, if we take long, it fails after say 1000000 or so. My objective is, not to increase the length of the code yet, do the same operation. I have already tried using a BIT wise XOR,
a = a ^ b;
b = a ^ b;
a = a ^ b;
Still it didn't help, any ideas?
To swap a variable a and a variable b: std::swap(a, b);
Example:
int a = 10;
int b = 20;
std::cout << "Before swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';
std::swap(a, b);
std::cout << "After swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';
Output using GCC 4.9.2:
Before swap
Value of a: 10
Value of b: 20
After swap
Value of a: 20
Value of b: 10
This way of doing it uses rvalues internally, so it has next to zero overhead for other use cases and won't overflow for any primitive type ever
Related
This question already has answers here:
What is the difference between prefix and postfix operators?
(13 answers)
Closed 12 months ago.
The community reviewed whether to reopen this question 12 months ago and left it closed:
Original close reason(s) were not resolved
I was working with my practicals and my tutor taught us the increment and decrement operators but I cannot understand a few things in code. The code is as follows :
#include < iostream >
using namespace std;
int main() {
int a = 10 , b = 100 , result_a , result_b ;
// Prefix Example
// Printing the value given by increment Operator on A
result_a = ++a;
cout << "Prefix Increment A : " << result_a << endl;
// Printing the value given by decrement Operator on B
result_b = --b;
cout << "Prefix Decrement B : " << result_b << endl;
cout << a << endl << b << endl;
// Postfix Example
// Printing the value given by increment Operator on A
result_a = a++;
cout << "Postfix Increment A : " << result_a << endl;
// Printing the value given by decrement Operator on B
result_b = b--;
cout << "Postfix Decrement B : " << result_b << endl;
cout << a << endl << b << endl;
cout << result_a << endl << result_b;
system("pause>0");
return 0;
}
And the output is as follows :
PS D:\Burhan\My coding projects\C++\WalletTerminal> if ( $? ) { g++
main.cpp -o main } ; if ( $? ) { .\main }
Prefix Increment A : 11
Prefix Decrement B : 99
11
99
Postfix Increment A : 11
Postfix Decrement B : 99
12
98
11
99
I don't understand why is the Postfix Increment A: 11 and Postfix Decrement B: 99 as my calculations say that it should be 12 and 98 which are the value of A and B. We are actually adding +1 to A and B but as far as I know, that happens after the line of code is executed but still, it doesn't work as intended. Can you please tell me how that works? I look on the internet but couldn't find any issues related to this.
You can look at it this way, when you use pre-increment or pre-decrement (++a, --b ) , what really happens is that for instance here
result_a = ++a;
What really happens is,( since ++ is a short-hand operator for incrementing)
a=a+1;
result_a=a;
Similarly for post-increment or post-decrement (a++,b--)
result_b = b--;
what really happens is
result_b=b;
b=b-1;
++a (Prefix) means firstly incrementing a and then using the value of a. a++ (Postfix) means firstly using the value of a and then incrementing a.
For example:
int a = 10;
std::cout << a++; // Will print out 10
// a == 11
int a = 10;
std::cout << ++a; // Will print out 11
// a == 11
This question already has an answer here:
`std::bitset` with and without boundary checks
(1 answer)
Closed 1 year ago.
Some data are stored in a 64 bit integer. As you can see, inside the getDrvAns function I check if the bit in the position drvIdx-1 is 0 or 1. One cannot be sure if the drvIdx will have a value in the right range (1-64). However, I noticed that if we put a value higher that 64, we have a wrap-around effect as demonstrated in the code below.
My question is, is this a standard behavior? Is it safe to leave it as it is without boundary checks?
Note: If the bit is set to 0 the drive has answered.
uint64_t mDrvAns = 48822;
bool getDrvAns(int drvIdx) {
std::bitset<64> bitRepOfmDrvAns{mDrvAns};
return (bitRepOfmDrvAns[drvIdx - 1] != 0ull);
};
std::string yesOrNo(bool val) {
return ((val==false) ? "Yes" : "No");
}
int main()
{
int drvIdx = 1;
std::bitset<64> bitsOfDrvAns{mDrvAns};
std::cout << bitsOfDrvAns << std::endl;
std::cout << "Has drv " << drvIdx << " answered? " << yesOrNo(getDrvAns(drvIdx))
<< std::endl;
drvIdx = 65;
std::cout << "Has drv " << drvIdx << " answered? " << yesOrNo(getDrvAns(drvIdx))
<< std::endl;
return 0;
}
According to the documentation, out of bounds access using operator[] is Undefined Behaviour. Don't do it.
If you don't want to check the bounds yourself, call test() instead, and be prepared to handle the exception if necessary.
Pretty basic code:
#include <iostream>
int main() {
std::cout.precision(100);
double a = 9.79999999999063220457173883914947509765625;
double b = 0.057762265046662104872599030613855575211346149444580078125;
const double bConst = 0.057762265046662104872599030613855575211346149444580078125;
double c = a * b;
std::cout << " a: " << a << std::endl;
std::cout << " b: " << b << std::endl;
std::cout << " bConst: " << bConst << std::endl;
std::cout << " c: " << c << std::endl << std::endl;
std::cout << " c/b: " << c / b << std::endl;
std::cout << " c/bConst: " << c / bConst << std::endl;
}
Which outputs:
a: 9.79999999999063220457173883914947509765625
b: 0.057762265046662104872599030613855575211346149444580078125
bConst: 0.057762265046662104872599030613855575211346149444580078125
c: 0.5660701974567474703547986791818402707576751708984375
c/b: 9.7999999999906304282148994388990104198455810546875
c/bConst: 9.79999999999063220457173883914947509765625
As you can see, b and bConst seem to be treated using the same value - i.e. it prints for both the same 0.057762265046662104872599030613855575211346149444580078125 value.
So I guess they are "stored" both the same. The only difference is that b is not const.
Then, I do the same c / b operation twice: one time using b, another time using bConst.
As you can see, it leads to two different results. And this makes me wonder.
Can you explain technically why this happens?
The "issue" is due to the -freciprocal-math switch (implied by -Ofast):
Allow the reciprocal of a value to be used instead of dividing by the value if this enables optimizations. For example x / y can be replaced with x * (1/y), which is useful if (1/y) is subject to common subexpression elimination. Note that this loses precision and increases the number of flops operating on the value.
The compiler can calculate d = 1/bConst at compile time and change from:
c/bConst
to
c * d
but multiplication and division are different instructions with different performance and precision.
See: http://coliru.stacked-crooked.com/a/ba9770ec39ec5ac2
You are using -Ofast in your link, which enables all -O3 optimizations and includes both -ffast-math, which in turns includes -funsafe-math-optimizations.
From what I could glean, with optimizations enabled, -funsafe-math-optimizations allows the compiler to reduce the precision of some computations. This seems to be what happens in the c/bConst case.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the correct answer for cout << c++ << c;?
I have following code -
int a= 7;
const int &b = a;
int &c = a;
if I use
cout << endl << ++c << '\t' << a << '\t' << b << '\t' << c;
it prints
"8 7 7 8"
however if I use
cout << endl << a << '\t' << b << '\t' << ++c << '\t' << a << '\t' << b << '\t' << c;
it prints
"8 8 8 8 8 8"
How exactly this happens ? Is it something related to optimization ?? If yes, how can i switch it off in ideone.com ???
Effectively the operator<< is a function call, c++ is allowed to evaluate the arguments passed to a function in any order it likes, hence the ++c inc is done first, quite legally, by your compiler - mine does something different.
Interstingly my compiler prints
8 8 8 7 7
Some compilers provide switches for order of evaluation of function params, but if you really need to use it I would question myself on the reasons for this as there is something much more wrong with the code and instead write it in a portable way.
a, b, and c are all the same object. The order in which the arguments to functions are evaluate is undefined, however. So, you whatever the compiler chooses to evaluate first is OK. It seems, in your second expression it evaluates ++c first. The way to avoid problems is not to fold the modification with the rest of the expression, i.e., to increment c either before or after the output.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Undefined Behavior and Sequence Points
I'm having trouble understanding the order of actions when overloading the postfix operator. Let's examine the two small examples below:
int i = 0;
std::cout << std::endl << "i: " << i;
i = ++i;
std::cout << std::endl << "i: " << i;
i = i++;
std::cout << std::endl << "i: " << i;
MyClass myObject;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
myObject = ++myObject;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
myObject = myObject++;
std::cout << std::endl << "myObject: " << myObject.getMyValue();
Two very different behaviors emerge. The output is as follows:
i: 0
i: 1
i: 2
myObject: 0
myObject: 1
myObject: 1
Different behavior, you see. Here's the outline of my overloaded-operator methods.
MyClass & MyClass::operator++ ()
{
++myValue;
return *this;
}
MyClass MyClass::operator++ (int postfixFlag)
{
MyClass myTemp(*this);
++myValue;
return myTemp;
}
Alright. Prefix makes sense. You increment whatever you need to, then return the same object, now modified, in case of assignment. But postfix is what's tripping me up. It's supposed to assign, then increment. Here we're self assigning. So with the built-in integer type, it makes sense. I assign i's value to itself, then i gets incremented. Fair enough. But let's say MyClass is a recreation of the int. It starts out at 0, gets prefix-incremented, and becomes 1. Then, the key line. myObject = myObject++. That's the same thing as myObject = myObject.operator++(int postfixFlag). It gets called. myTemp gets initialized with the value 1. It's incremented to 2. Then we return the temp. That works, if we're assigning to another object. But here I'm self-assigning, so after the increment to 2, myObject is set equal to the returned temp object initialized with the initial value, and we're back to 1! That makes sense. But it's a fundamentally different behavior.
How do I work around it? How does int do it? How is this method generally written? Do you have any comments about C++ behavior and design relating to this? Etc. I'm a little perplexed right now, since books and online examples always seem to use a variant on the method above.
Thanks for reading, and any input will be appreciated!
As others have said, with int the behaviour is undefined. But I thought I'd try to explain why for your MyClass it is not ever getting to 2.
The trick is that you are taking the following three steps in the postfix version:
Making a copy of this called myTemp (with myValue == 1).
Incrementing this->myValue (so myTemp.myValue == 1; this->myValue == 2).
Returning myTemp (with myValue == 1).
So you are modifying this, but the code that calls myObject++ is never going to see this again. It's only going to look at the value returned, which is a copy of the old myObject.
The code for operator++ is fine. The problem is how you are using it -- you shouldn't be writing the result of a pre-increment or post-increment back to the same variable (behaviour is undefined). Here is some code that might be more instructive:
int i = 0;
std::cout << "i: " << i << std::endl;
int j = ++i;
std::cout << "i: " << i << ", j: " << j << std::endl;
int k = i++;
std::cout << "i: " << i << ", k: " << k << std::endl;
MyClass myObject;
std::cout << "myObject: " << myObject.getMyValue() << std::endl;
MyClass myObject1 = ++myObject;
std::cout << "myObject: " << myObject.getMyValue()
<< ", myObject1: " << myObject1.getMyValue() << std::endl;
MyClass myObject2 = myObject++;
std::cout << "myObject: " << myObject.getMyValue()
<< ", myObject2: " << myObject2.getMyValue() << std::endl;
This prints:
i: 0
i: 1, j: 1
i: 2, k: 1
myObject: 0
myObject: 1, myObject1: 1
myObject: 2, myObject2: 1
I changed your code so that rather than assigning back to itself, it assigns to a fresh variable each time. Note that in both the int and the MyClass cases, the main variable (i/myObject) is incremented both times. However, in the pre-increment case, the fresh variable (j/myObject1) takes on the new value, while in the post-increment case, the fresh variable (k/myObject2) takes on the old value.
Edit: Just answering another part of the question, "How does int do it?" I assume this question means "what does the pre-increment and post-increment code look like in the int class, and how can I make mine the same?" The answer is, there is no "int class". int is a special built-in type in C++ and the compiler treats it specially. These types aren't defined with ordinary C++ code, they are hard-coded into the compiler.
Note: For anyone who wants to try this themselves, here is the code for MyClass that the question didn't include:
class MyClass
{
private:
int myValue;
public:
MyClass() : myValue(0) {}
int getMyValue() { return myValue; }
MyClass& operator++();
MyClass operator++(int postfixFlag);
};