Decrement Operator in C++ - c++

I am from C background, and now I am learning OOP using C++
Below is a program that calculates factorial.
#include <iostream>
using namespace std;
void main ()
{
char dummy;
_int16 numb;
cout << "Enter a number: ";
cin >> numb;
double facto(_int16);
cout << "factorial = " <<facto(numb);
cin >> dummy;
}
double facto( _int16 n )
{
if ( n>1 )
return ( n*facto(n-1) );
else
return 1;
}
The above code works fine.
But if I replace the return statement
return ( n*facto(n-1) );
with this
return ( n*facto(n--) );
then it doesn't work. The n-- won't decrement n by 1. Why?
I am using Visual Studio 2012
Edit:Got it! thanks :)
*also, I would like to add to the answers below: using --n will cause the n to decrement before the statement is executed. So, due to pre-decrement, the expression will become (n-1)*facto(n-1) . That is why it is better not to use pre-decrement in this case *

Currently, by using n-- you are passing the original and therefore unmodified value of n into facto which is causing a loop.
You need to use n - 1 instead. It would, on the face of it, be tempting to use --n since that would decrement n and evaluate to the new (lower) value. But --n will give you undefined behaviour since you are pre-multiplying the function return value by n and since * is not a sequence point, the value of n is not well-defined.
(By the way, the behaviour in C would have been identical).
[Edit: acknowledge Mike Seymour on the undefined behaviour point].

EDIT:: The explanation below is only to shed light on the usage of Post and Pre-Decrement for OP's better understanding of them. The correct answer for OP's code is, n*facto(n - 1). #OP: You should not do any pre-drecrement in that part of your code because it will invoke Undefined Behavior due to unsequenced modification of variable n.
Pre And Post-Decrement::
You have to use pre-decrement (wiki-link) if you want to decrement the variable before the value is passed. On the other hand, a post-decrement evaluates the expression before the variable is decremented:
int n = 10, x;
x = --n; // both are 9
and
int n = 10, x;
x = n--; // x = 10, i = 9
Why not to use pre-decrement in your case?:: n*facto(n--) causes UB.
Why?
The Standard in §5/4 says
Between the previous and next sequence point a scalar object shall
have its stored value modified at most once by the evaluation of an
expression.
and
The prior value shall be accessed only to determine the value to be
stored.
It means, that between two sequence points a variable must not be modified more than once and, if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

return ( n*facto(n--) );
You are using the post decrement operator.
What happens is, You pass the value of n to the function and then decrement it. That doesn't affect the value that is already passed to the function

Related

String reverse function is not working for odd length strings

I tried to write the following code in C++ to reverse a string. For some reason, when the string is of odd-length it gives a wrong output.
#include <iostream>
using namespace std;
void swapWithOutThirdVar(char &a, char &b) {
a = a + b;
b = a - b;
a = a - b;
}
void reverse(char string[]) {
int length = 0;
while (string[length] != '\0') {
length++;
}
int left = 0, right = length - 1;
while (left <= right) {
swapWithOutThirdVar(string[left], string[right]);
left++;
right--;
}
}
int main() {
char string[25];
cin>>string;
reverse(string);
cout<<string<<endl;
}
For example if I enter lappy to the console, the subsequent output is yp. I am new to programming, so please be kind to me no matter how stupid the underlying mistake is.
There are many ways to resolve the error in your code, but the backbone error in your code lies in the swap function that you have defined on your own.
void swapWithOutThirdVar(char &a, char &b) {
a = a + b;
b = a - b;
a = a - b;
}
I know that this is a very well-known function used to swap two variables without using a third variable. But it has two issues:
For certain values of a and b, the operation a + b can result in an overflow.
(This is the case here) If you run into passing the exact same variables to the function, the swap would end up being erratic. Here's why:
Let's say that you're passing the variable char c to both the arguments of the function. Since in your function the parameters are being passed by reference, the dummy variables a and b are actually the same variables, that is, they're aliases to the same c. In a nutshell, a and b denote the same variable c.
So, now when you do a = a + b, the operation actually results in c = c + c, which means that c's (ASCII) value has been doubled by the end of execution of this statement.
The fun hits when the second statement comes into play. b = a - b results in c = c - c, which assigns 0 to c. That's where you went wrong, kiddo.
The third statement doesn't do anything good to the process. a = a - b results in c = c - c, which still makes c hold 0.
So, your variable gets assigned the value 0, instead of getting swapped with (itself?).
Now, you might be wondering where are you exactly ending up swapping the same variable, right?
When you're having an odd-length string, note that in the last iteration of the second while loop, the values of left and right are the same. In that case, left and right have the same indices for string and hence string[left] and string[right] are the same variables. The same variables are being passed to the swap function in that iteration.
Now, as I had stated earlier: passing the same variables to the swap function will end up handing a 0 to the variable that has been passed to it. For your example case, this is what string looks like at the end of the last iteration:
['y', 'p' '\0', 'a', 'l']
In C/C++, a null (0) marks the end of a string. Therefore, the weird output (yp) is justified.
In even-length strings, left will never be equal to right in any of the iterations of the second while loop. That's why, a same variable is never passed to the swap function, and that's why the reverse function works just as fine as the same variable is never passed to it.
Therefore, firstly you need to take care of the same-variable case. In case a and b are the same variable, you simply return from the function as swapping a variable with itself is techically pointless. Utilise the fact that if two variables are basically references to the same variable, they must be having the same address.
void swapWithOutThirdVar(char &a, char &b) {
if (&a == &b)
return;
a = a + b;
b = a - b;
a = a - b;
}
But this doesn't resolve the overflow issue. So, you need to do something else.
Assuming that this is a programming assignment problem in which you need to implement everything on your own, you can go for the XOR-swap which uses bitwise XOR to swap two variables. Going by the name of your swap function, I think you're aware of the vintage three-variable swapping technique and that using a third variable for swapping is also a restriction in your assignment.
Operating XOR on two numbers doesn't result in overflow, so that problem is fixed. The XOR method although, doesn't independently resolve the same-variable case and ends up handing the variable a 0 in the first statement itself, so you need to retain the address equality checking part:
void swapWithOutThirdVar(char &a, char &b) {
if (&a == &b)
return;
a ^= b;
b ^= a;
a ^= b;
}
Also, you can leave the swap function as it is and slightly modify the second while loop's condition to resolve the error:
For an odd-length string, the middle character's position is left unchanged when reversed. Come to think of it: the left-equals-right case arises when left and right (both) are pointing to the middle character of the string. So, the loop needs to run only as long as left < right holds true. For an even-length string, left never becomes equal to right. The while loop ends right when left and right are indices of the two adjacent middle elements of the string. Therefore, the left < right modification doesn't hurt the even-length case. So, the corresponding fix would be:
void reverse(char string[]) {
int length = 0;
while (string[length] != '\0') {
length++;
}
int left = 0, right = length - 1;
while (left < right) {
swapWithOutThirdVar(string[left], string[right]);
left++;
right--;
}
}
This concludes the bug explanation and rectification part. But in case this isn't for a programming assignment in which you have to implement everything on your own, that is, you don't have restrictions, you should consider the following instead:
Judging by the using namespace std; in your code, it appears that it was meant for C++0x or beyond. So, you should be considering the following things:
From C++0x onwards, you already have a predefined swap function (std :: swap). You can use that instead. Overflows and same-variables being passed to it aren't an issue here. See here.
You're using a C-style string in your program. C-style strings are not recommended anymore. Moreover, you're using C++0x or beyond. So, you should be using std :: string instead. See here.
You can use the reverse function from the algorithm header. See here.
Your swap implementation is incorrect if a and b point to the same memory location.
So you shall fix your loop:
while (left < right) {
swapWithOutThirdVar(string[left], string[right]);
left++;
right--;
}
This is a peculiarity of C++'s call-by-reference semantics. Your swap function will give unexpected (and incorrect) results when both &a and &b are the same memory address. This occurs when left == right.
Consider the following substitution, where I've changed a and b to both be the same variable, middleLetter:
middleLetter = middleLetter + middleLetter;
middleLetter = middleLetter - middleLetter;
middleLetter = middleLetter - middleLetter;
The second line sets middleLetter to zero, and the third line leaves it as zero.
The simple fix is to change your loop condition to while(left < right). There is no need to swap the middle letter with itself anyway.

Postfix and prefix increment that causes an error

Why does that code does not compile due to an error:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
cout << ++(i++) << " " << i << endl;
return 0;
}
While that code does compile:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
cout << (++i)++ << " " << i << endl;
return 0;
}
I do not understand that. From my point of view it would be pretty reasonable for the first chunk to compile. The expression ++(i++) would just mean take i, increment it and output, then increment it again.
I am not asking about an undefined behavior in int overflow. I do not know about r and l value at all at the time of writing the question and I do not care why is ++i considered an l-value, but i++ is not.
This is because the post increment and pre increment operators return values with different types. Result of post increment is a so-called 'rvalue', meaning it can not be modified. But pre-increment needs a modifiable value to increment it!
On the other hand, result of pre-increment is an lvalue, meaning that it can be safely modified by the post increment.
And the reason for above rules is the fact that post-increment needs to return a value of the object as it was before increment was applied. By the way, this is why in general case post-incrememts are considered to be more expensive than pre-increments when used on non-builtin objects.
Shortly speaking the difference is that in C++ you may use any even number of pluses (restricted only by the compiler limits) for the prefix increment operator like this
++++++++++++++++i;
and only two pluses for the post increment operator
i++;
The postfix increment operator returns a value (The C++ Standard, 5.2.6 Increment and decrement)
1 The value of a postfix ++ expression is the value of its
operand. [ Note: the value obtained is a copy of the original value
—end note ]
While the prefix increment operator returns its operand after increment (The C++ Standard ,5.3.2 Increment and decrement)
1 ...The result is the updated operand; it is an lvalue...
Opposite to C++ in C you also can apply only two pluses to an object using the prefix increment operator.:) Thus the C compiler will issue an error for such an expression like this
++++++++++++++++i;
When you compile it with clang you get error message that says it all.
<source>:8:13: error: expression is not assignable
cout << ++(i++) << " " << i << endl;
Maybe it is good to start with ++ operator. In fact it is shorthand for i = i + 1. Now if we look at postfix version i++, it says in standard that it returns copy of original value and as side efect it increments original value.
So from (i++) you get rvalue and are trying to assign to it and as we know you can't assign to rvalue.

Is using an assignment operator in a function argument undefined behaviour?

I found some code similar to this in an example my university tutor wrote.
int main(){
int a=3;
int b=5;
std::vector<int>arr;
arr.push_back(a*=b);
std::cout<<arr[0]<<std::endl;
}
Is there a well-defined behaviour for this? Would arr[0] be 3 or 15 (or something else entirely)?
Visual Studio outputs 15, but I have no idea if that's how other compilers would respond to it.
Before push_back is executed, the expression passed as argument will need to be computed. So what is the value of a *= b. Well it will always be a * b and also the new value of a will be set to that one.
It's valid and works as you expect.
The expression is first evaluated and the result is "returned".
auto& temp = (a*=b);
arr.push_back(temp);
The value of an expression with the compound assignment operator is the value of the left operand after the assignment.
So the code your showed is valid. Moreover in C++ (opposite to C) the result is an lvalue. So you may even write :)
arr.push_back( ++( a *= b ) );
In this case the next statement outputs 16.:)

condition operator and arrays / returning an pointer to array

I was hoping someone could explain how the condition statement of return (i % 2) ? &odd : &even; is able to determine if i is even or odd.
I am confused because &odd and &even are references to int odd[] and int even[]. It is my understanding the a condition statement does not "iterate" through the array and check all values in the array in order to check the condition of (i % 2) for a match. below is the code. I hope I was clear enough.
#include <iostream>
int odd[] = { 1, 3, 5, 7, 9 };
int even[] = { 0, 2, 4, 6, 8 };
decltype(odd)* arrptr(int i) { // equivalent to int (*arrPtr(int))[5] or
// auto arrPtr(int i) -> int(*)[5]
return (i % 2) ? &odd : &even;
}
int main()
{
arrptr(3);
system("pause");
return 0;
}
This is to explain the confusion you've as I see in the comments you posted to the other answer.
How does the conditional statement know the difference between what is a even number or an odd number?
It doesn't. It simply evaluates the first expression and checks the truth value. Like an if, you insert the logic on deciding if i is even or odd. Usually this is done with the interger reminder operator i % 2.
The expressions in the conditional statement are nothing more than references to an array named &odd[] and &even[]. There is nothing in the program that tells the program what even or odd number means.
No, the second and the third arguments are what &odd[] and &even[] are. You missed the first; it is a conditional expression which will be evaluated for a truth value.
i % 2 will return 0 if i is even, else 1 if i is odd. This integer value will be implicitly converted into a boolean value since the expression is evaluated in a boolean context. In C and C++ any non-zero value is true else false. Hence if i is even it'll return false, else true.
I think what is confusing you is the name of operands 2 and 3; mentally rename them into evenArray and oddArray. What the operator does is, it returns an array. Which array? That it decides based on the first operand, which in turn decides it with parity (even/odd) of the argument i.
That is the C conditional operator ?:. The part before the question mark is a Boolean expression. If it evaluates to true then the part between the questions mark and the colon is executed otherwise the other part is executed. It's equivalent to:
if(boolean expr) { expression1 }
else { expression2 }
In your example, you could write:
decltype(odd)* arrptr(int i)
{ if(i % 2) return &odd;
else return &even;
}
You might be confused by how the arrays are named. The function returns a pointer to an array depending on the value of i (the function knows nothing about the numbers stored in the arrays). That is, if i is an odd number we return a pointer to the array named odd and if it i is even we return a pointer to the array named even. The i % 2 part tells you if i is even or odd. Hope this helps.

Using the comma operator in if statements

I tried the following:
if(int i=6+4==10)
cout << "works!" << i;
if(int i=6+4,i==10)
cout << "doesn't even compile" << i;
The first works fine while the second doesn't compile. Why is this?
EDIT: Now I know that the first one may not work as I intend it to. The value of i inside the if scope will be 1, not 10. (as pointed out by one of the comments on this question).
So is there a way to initialize and use a variable inside of an if statement at the same time similar to for(int i=0;i<10;i++)? So that you could produce something like if((int i=6+4)==10) (which will not compile) where the value of I inside the if scope would be 10?
I know you could declare and initialize I before the if statement but is there a way to do this within the statement itself?
To give you an idea why I think this would be usefull.
if(int v1=someObject1.getValue(), int v2=someObject2.getValue(), v1!=v2)
{
//v1 and v2 are visible in this scope
//and can be used for further calculation without the need to call
//someObject1.getValue() und someObject2.getValue() again.
}
//if v1==v2 there is nothing to be done which is why v1 und v2
//only need to be visible in the scope of the if.
The expression used as an initializer expression must be an assignment-expression so if you want to use a comma operator you must parenthesize the initializer.
E.g. (not that what you are attempting makes much sense as 6 + 4 has no side effects and the value is discarded and i == 10 uses the uninitialized value of i in its own initializer.)
if (int i = (6 + 4, i == 10)) // behaviour is undefined
Did you really mean something like this?
int i = 6 + 4;
if (i == 10)
When using the form of if that declares a new variable the condition checked is always the value of the initialized variable converted to bool. If you want the condition to be an expression involving the new variable you must declare the variable before the if statement and use the expression that you want to test as the condition.
E.g.
int i;
if ((i = 6 + 4) == 10)
I doubt seriously either example works to do anything useful. All that it does is evaluate to "true" in a complicated fashions.
But the reason the second one doesn't compile is that it's interpreted as two declarations: int i = 6+4; int i==10 and int i==10 isn't valid because that's an equality operator, not an assignment.
There are different alternatives, because what you want cannot be done (you cannot mix the comma operator with declarations). You could, for example, declare the variable outside of the if condition:
int i = 6+4;
if ( i == 10 ) ...
Or you can change the value of i to be 0 instead of 10 and recalculate i inside the else block:
if ( int i = (6+4)-10 ) ; else {
i += 10;
// ...
}
Much simpler, don't declare the variable at all, since you know the value inside the loop:
if ( (6+4)==10 ) {
int i = 10;
// ...
}
Unless of course you need the value of i in the case where it is not 10, in which case the second option is the most appropriate.
As of C++17 what you were trying to do is finally possible:
if (int i=6+4; i==10)
cout << "works, and i is " << i << endl;
Note the use of ; of instead of , to separate the declaration and the actual condition.