Define not evaluating POD? - c++

I was going over the C++ FAQ Lite online. I was browsing inlines again since I haven't found a use for them and wanted to know how the stopped the circular dependency as showed in this answer. I first tried to do the, "Why inlines are better than defines." example with the following code:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
inline
int safe(int i)
{
return i >= 0 ? i : -(i);
}
int f();
int main(void)
{
int x(5);
int ans;
ans = unsafe(x++);
cout << ans << endl;
ans = unsafe(++x);
cout << ans << endl;
ans = safe(x++);
cout << ans << endl;
ans = safe(++x);
cout << ans << endl;
std::cin.get();
return 0;
}
EDIT:
Great. Got the typo out of the way. Not that I'm bitter that I don't find such errors or anything.
The output is now 6, 9, 9, 11.
However, even with pre-incrementation, shouldn't the first value result in 7?
If the macro is being called twice, then doesn't it go like this:
unsafe(x) // pre-incrementation doesn't modify the value when called.
unsafe(++x) // for all intents and purposes, the incrementation happens before the second call, so the ++x. This is for the first ans = unsafe(x++) if it's being called twice.
By the time we reach the second ans = unsafe(++x), shouldn't the x have been incremented twice? Once by the double call and once when the first double call was finished?

Instead of:
#define unsafe(i) \
( (i) >= 0 = (i) : -(i) )
I think you want:
#define unsafe(i) \
( (i) >= 0 ? (i) : -(i) )
In response to your edit:
After the first call to unsafe(x++), x is 7, even though the ans is 6. This is because you have the statement:
ans = ( (x++) >= 0 ? (x++) : -(x++) )
ans is assigned to the middle x++ after the left-most x++ is evaluated. As a result, ans == 6 but x == 7. The difference with unsafe(++x) is that ans is assigned to ++x, meaning the result is ans == x == 9.

Related

Why does results are different when relational operators means the same?

For clarification, let's consider the following program:
#include <iostream>
int main(void) {
short int i; // declaration
short int value;
short int sum;
i = value = sum = 0; // initialization
std::cout << "Enter a value: ";
std::cin >> value;
while (i != value) { // ### here's the confusion ###
sum += i;
i++;
}
std::cout << "Total sum: " << sum << std::endl;
return 0;
}
Look at the while (i != value), when this expression is given, the results shows Total sum: 45 whereas if we put while (i <= value), it shows Total sum: 55. (Input's given 10 for example)
Here, the confusion is, when should we use != and <= or >= operations in loops, any specific condition?
According to TutorialsPoint's Operators Reference
it tells that != (returns true used when two operands are unequal).
<= (returns true when used when we need to ensure if the first operand is lesser than or equal to second).
It was expected to get no difference in output, but something's misunderstood.
This while loop
while (i != value)
does not include the iteration when i is equal to value because in this case the condition i != value evaluates to false.
This while loop
while (i <= value)
includes the iteration when i is equal to value because in this case the condition i <= value evaluates to true.
In fact the first condition can be rewritten the following way (provided that initially i is less than value)
while ( i < value )
Now compare it with the condition in the second loop that in turn can be rewritten like
while ( i < value || i == value )
That is you have two different conditions.
With
while( i <= value)
the last iteration is with i == value. With
while ( i != value)
The body of the loop will not be executed when i == value. That is the reason you observe the difference.
This is a good chance to learn how to use a debugger. And/Or realize that your example is already too complicated to directly see what is going on. You would have spotted the difference more easily with
int i = 0;
int value = 5;
while ( i != value) {
std::cout << i << " ";
}
i = 0;
while ( i <= value) {
std::cout << i << " ";
}

What does this arithmetic expression mean: A += B++ == 0 in C++;

I came accross this expression, and can't understand the meaning of line 3 in the following snippet:
int A=0, B=0;
std::cout << A << B << "\n"; // Prints 0, 0
A += B++ == 0; // how does this exp work exactly?
std::cout << A << B << "\n"; // Prints 1, 1
A adds B to it, and B is Post incremented by 1, what does the "==0" mean?
Edit:
Here's the actual code:
int lengthOfLongestSubstringKDistinct(string s, int k) {
int ctr[256] = {}, j = -1, distinct = 0, maxlen = 0;
for (int i=0; i<s.size(); ++i) {
distinct += ctr[s[i]]++ == 0; //
while (distinct > k)
distinct -= --ctr[s[++j]] == 0;
maxlen = max(maxlen, i - j);
}
return maxlen;
}
B++ == 0
This is a boolean expression resulting in true or false. In this case the result is true, true is then added to A. The value of true is 1 so the (rough) equivalent would be:
if(B == 0)
A += 1;
++B;
Note that this isn't particulary good or clear to read code and the person who wrote this should be thrown into the Gulags.
Lets break this expression into pieces: A += value, whereas value = B++ == 0. As later cout suggests, value == 1. Why is that? Here is why: value is result of comparison of B++ and 0, but ++ (increment) operation, when written after operand, is being processed after the comparison, i.e. if you write A += ++B == 0 the later cout should (and does) print 0, 1.

Difference between pre and post decrement in recursive function argument

I have following sample code where i used pre-decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(--c);
cout << c << endl;
return;
}
}
This function give output for input 4 as :
DP3
DP2
DP1
DP0
0
1
2
3
But when i use post decrement
void function(int c)
{
if(c == 0)
{
return;
}
else
{
cout << "DP" << c << endl;
function(c--);
cout << c << endl;
return;
}
}
Output goes in infinite loop with DP4
Can you explain me in detail why this happens ?
This happens because function(c--) will be called with the same value of c and when it finishes c will be decremented. But as it is recursively called, hence it will be called with same value with no chance of return and eventually you will hit stack overflow error.
Assume this, int x = 1, y = 0; Now y = x++ will result y == 1 and x == 2. But if you do y = ++x , then bot x and y will be 2.
Because --c will return c-1,however c-- return c.So when you use function(c--) is equal to function(c);c = c-1;.c will never be 0.So the function won't stop.
To know the difference between --x and x-- you can try the following code:
int x = 5,y=5;
cout<<x--<<endl;
cout<<--y<<endl;
cout<<x<<" "<<y<<endl;
In case of post decrement value will be passed before decrement , always same value will be passed to function , it never come out .
function(c--), first it call function(c) later decrement c-- will happen .

What's wrong with my while loop condition code?

I wrote the following code, but after I compiled it, and run it, nothing happens. I can't figure out what's wrong with it.
There are two "and conditions" in the while loop. When I take out 1 condition, it works fine, but when I put both conditions in, it no longer works.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter an integer greater than 10: ";
cin >> n;
int c=1;
while ( (c*5 <= n*2) && (c*5 >= n) ) {
cout << c*5 << endl;
c = c+1;
}
return 0;
}
Your condition will never be true. You start with n > 10, let's say n == 11. Initially, c == 1.
Your condition is:
while ( (c*5 <= n*2) && (c*5 >= n) )
so that's:
while ( (1*5 <= 11*2) && (1*5 >= 11) )
or
while ( (5 <= 22) && (5 >= 11) )
5 is less than 11, so 5 >= 11 is false, and the loop never runs.
If n is greater than 10, then c*5 (ie. 5) will not be >=n so the loop condition will be false on the first evaluation.

Multiple if statements in C++

I'm doing the first project euler problem and I just did this
#include <iostream>
using namespace std;
int main(){
int threes =0;
int fives = 0;
int both = 0;
for (int i = 0; i < 10; i++){
if(i%3==0){
threes += i;
}
if(i%5==0){
fives += i;
}
if ( i % 5 == 0 && i % 3 == 0){
both += i;
}
}
cout << "threes = " << threes << endl;
cout << "fives = " << fives << endl;
cout << "both = " << both << endl;
cout << " threes + fives - both = " << endl;
int result = (threes + fives) - both;
cout << result<< endl;
return 0;
}
My professor recently corrected me for doing this in a different problem saying something about else statements,
but I don't understand WHY i have to add else in front of the next if. for what its worth I have another version with else if(i%5){ fives += .... }
and they both work and get me the right answer.
My question is whats inherently wrong with this way of thinking, is it stylistic or am I not thinking logically about something?
If it works, why use switch statements ever?
The only thing that I see wrong with your implementation is that in the case where the number is both a multiple of 3 and a multiple of 5 not only is the both variable incremented but the fives and threes variables are also incremented. Based on what the professor described I believe he wants you to use an else-if so that the both variable is the only one that is incremented when you pass in a number that is both a multiple of 3 and a multiple of 5.
The reason you get the correct answer both ways is because you are only going to 10 in the for loop, if you increase it to i <= 15 you will get fives and threes being 1 higher than I think he intended.
For example:
for( int i = 0; i < 10; i++ )
{
if( ( ( i % 3 ) == 0 ) && ( ( i % 5 ) == 0 ) )
{
both++;
}
else if( ( i % 3 ) == 0 )
{
threes++;
}
else if( ( i % 5 ) == 0 )
{
fives++;
}
}
The else branch in an if-else statement is only executed if the if branch is false. If you just have two if statements in a row, they'll both be executed, which can be a waste. In the below code, the else prevents the second computation from running if the first is satisfied.
if (expensive_computation1()) {
...
}
else if (expensive_computation2()) {
...
}
Additionally, it's clearer to humans reading the code whether both if statements should be allowed to run or whether only one should.
In this case, maybe you really want this:
if (i % 5 == 0 && i % 3 == 0) {
both += i;
} else if (i % 3 == 0) {
threes += i;
} else if (i % 5 == 0) {
fives += i;
}
(why you do += i instead of ++ I don't know but you didn't explain, so I just copied it)
In your code, threes and fives were incremented even if it would also increase both, which depending on your problem may not be what you want. If you do the if/else way I've just presented, only one of the three variables is increased.
Why use if-else instead of multiple if's?
if-else & if would achieve the same results but if-else achieves them in a performance enhanced way. with multiple if's every if condition will have to be checked. With if-else only one conditional check will have to be performed and the rest of the conditions just don't need to be checked at all.
This would not affect a small program like the one you have but it will sure have some impact in potentially expensive function being called repeatedly over and over again.
If it works, why use switch statements ever?
With nested if-else conditions the code is hard to read and understand. The switch-case construct helps to represent the conditions in a much easier to read & understand format.
To me it looks like stylistics. You can use some autoreformating tool that follows certain established stylistic look (K&R, ANSI, GNU, etc.)
For example astyle is such tool, http://astyle.sourceforge.net/ - just reformat your code with it, and you might have a happy professor.