when need to do this in c++; if(x = 0) {} - c++

I noticed sometimes developers do these in their project;
while(int x = 0) {//run code}
int y = 0;
if (y = someFunction())
{//run code}
I want ask;
why c++ allow to do these in loops like while,(maybe for as well?) and if-else statements, what is the usage?
when someone should do this in his project?
and when conditions like these give result true?

what is the usage?
Declaration inside if/for/while allows to reduce scope of the variable.
so, instead of
int y = somevalue();
if (y) {// y != 0
// ...
}
// y still usable :/
or
{ // extra block :/
int y = somevalue();
if (y) {// y != 0
// ...
}
}
// y no longer usable :)
you might directly do:
if (int y = somevalue()) // y != 0
// ...
}
// y no longer usable :)
with syntax which might indeed surprise.
For more controversial:
int y;
// ...
if (y = somevalue()) // y != 0
// ...
}
// y still usable :)
it is allowed as that assignation is an expression convertible to bool (value of y = x is y (which has been assigned to x)).
it is more controversial as error prone as unclear if = or == is expected.
some convention use extra parents to more clearly express assignation
if ((y = somevalue())) // really = intended, not ==
// ...
}
when someone should do this in his project?
For existing projects, try to use existing convention.
For new project, you have to do the trade of:
scope versus syntax not shared with other language which might be surprising
and when conditions like these give result true?
when given expression convert to true, so non zero integral, non null pointer.
c++17 introduces another syntax to allow to split declaration and condition for if/while. (for already allow that split)
if (int y = somevalue(); y != 42) // y != 42
// ...
}
// y no longer usable :)

Related

use of 'n' before deduction of 'auto' C++

I'm trying to have my function return 3 values (n, down and across) I've read online how 'auto' can be used but must be doing something wrong.
The function takes in a 2D vector of integers (as well as other variables) and checks for how many numbers are connected to board[0][0] such that they are the same number.
I've tried putting auto in front of the function inside the function itself, tried leaving it blank, tried just having chain = chainNodes(...) but I always seem to get an error. Here's the code:
tuple<int, int, int> chainNodes(vector<vector<int>> board, int originalNum,
unsigned int across, unsigned int down, int ijSum,
int n)
{
struct chain {
int n, down, across;
};
if(down + across > ijSum) {
ijSum = down + across;
} else if((down + across == ijSum) &&
((down - across) * (down - across) < (ijSum) * (ijSum))) {
ijSum = down + across;
}
board[down][across] = 0;
n += 1;
// Check below
if((down != (board.size() - 1)) && (board[down + 1][across]) == originalNum) {
down += 1;
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
down -= 1;
}
// Check right, up and left (I've removed so its not too messy here)
return chain{n, down, across};
}
Sorry, I forgot to include the error message.
error: use of 'n' before deduction of 'auto'
It occurs on the line that uses auto.
Issue with
auto [n, iPoint, jPoint] = chainNodes(board, originalNum, across, down, ijSum, n);
is similar to
auto n = foo(n); // `foo(n)` uses `n` from `auto n`,
// not the one from outer scope as function parameter
The construct int a = a + 1; is legal but lead to UB as reading uninitialized variable.
That kind of construct allows legal and valid behavior void* p = &p;.
Your code has other errors and it is not clear for me expected behavior of the function.
So not sure if following is the correct fix, but you might want:
n = std::get<0>(chainNodes(board, originalNum, across, down, ijSum, n));

bool returning recursive function alters variable unexpectedly

Could someone explain to me what happens in this? From the little knowledge I have(and clearly I am wrong in my thinking), to me this should keep decreasing x by 1 until x is 3. Then it should go to the 'return true, part and as the function returns true, it goes back to the second if statement, return false and then exit the function since there is nothing to do if the function returns false. But this keeps going back to the second if statement adding 1 to x until it is 9 again and then exits. Thanks in advance.
bool Rec(int x)
{
if( x > 3)
{
if(Rec(x - 1) == true)
{
return false;
}
else
{
return false;
}
}
else
{
return true;
}
}
void main()
{
Rec(9);
}
Actually I don't see a problem with the way your code functions. It actually works.
It can be simplified and is equivalent to:
#include <stdio.h>
bool Rec(int x)
{
printf("x = %d\n", x);
if (x > 3)
{
Rec(x - 1);
return false;
}
return true;
}
int main(int argc, char* argv[])
{
Rec(9);
return 0;
}
Which produces:
x=9
x=8
x=7
x=6
x=5
x=4
x=3
However you've also said: "But this keeps going back to the second if statement adding 1 to x until it is 9 again and then exits". But you're not actually adding 1 to x. I think what's going on is to do with your debug. You haven't put any debug in your code to print out said behaviour.
So I'll attempt to do it for you.
bool Rec(int x)
{
printf("x = %d\n", x);
if (x > 3)
{
Rec(x - 1);
printf("*x = %d\n", x);
return false;
}
return true;
}
Which produces:
x = 9
x = 8
x = 7
x = 6
x = 5
x = 4
x = 3
*x = 4
*x = 5
*x = 6
*x = 7
*x = 8
*x = 9
Think about this carefully. You're not adding 1. Your function is calling itself again printing x = and then if it's greater than 3 doing the same. Only when x > 3 does it return. After it returns it will again print *x =
So it's actually printing what x was before the recursive call. I hope that helps you see what's going on.
Your function is fine to see how recursion works. But in practice you'd never write code like that. Because you could just write it as a simple loop.
Avoid recursion if you can come up with code using a loop. But sometimes, recursion is easier. For example, traversing binary trees is really simple with recursion.
There are some answers on this question here which give real world examples of where recursion makes sense. Real-world examples of recursion
This is the nature of the recursion. You called function 6 times, it is going to return 6 times.

XOR operator not evaluating correctly in C++

I'm building a BigInt class from scratch in C++, but something is driving me nuts: my XOR isn't working properly, and I have no idea why. I was hoping someone could enlighten me. Below is a minimal working example:
class BigInt
{
private:
bool pos;
int size; // Number of binary digits to use
short compare(BigInt input);
public:
BigInt(long long input, int inSize) { pos = true; size = inSize; }
};
short BigInt::compare(BigInt input)
{
// Partial compare function for minimal working example
// Return:
// 1: (*this) > input
// 0: (*this) == input
// -1: (*this) < input
string a = (*this).toDecimal(), b = input.toDecimal();
bool c = (*this).size > input.size, d = (*this).pos ^ input.pos;
bool thispos = (*this).pos, inpos = input.pos;
bool xorpos = (thispos != inpos);
bool x = true, y = true;
bool z = x ^ y;
if ((*this).size > input.size || (*this).pos != input.pos)
return 1 - ((*this).pos ? 0 : 2);
else if ((*this).size < input.size)
return -1 + ((*this).pos ? 0 : 2);
return 0;
}
I have a breakpoint on the first if statement. Below is what I have on my watch list.
thispos true bool
inpos true bool
xorpos true bool
x true bool
y true bool
z false bool
Anyone know what's going on? I'd rather avoid kluging my if statement. I've never had a problem with such simple usage of my XOR.
As far as I can tell, there should be nothing wrong, but there's something about these values that just won't evaluate the way they're expected to.
Edit: Changed code to minimal working example.
Well, even though ^ is a bitwise xor operator, your initializations
bool thispos = (*this).pos, inpos = input.pos;
are required to convert the source values to bool type. Values of bool type are guaranteed to act as either 0 or 1 in arithmetic contexts. This means that
bool xorpos = thispos ^ inpos;
is required to initialize xorpos with false if both thispos and inpos were originally true.
If you observe different behavior, it might be a bug in your compiler. Integral-to-bool conversion might be implemented incorrectly or something like that.
Another opportunity is that someone "redefined" the bool keyword by doing something like
#define bool unsigned char
This will disable the proper bool semantics in the first pair of initializations and cause the bitwise nature of ^ to affect the result.
Why not simply do x != y? This is more consistent with your types as well.

C++ FAQ example on inline vs. #define

There is an example on the FAQ to explain the difference between inline and #define. The code is here
and the link is: http://www.parashift.com/c++-faq/inline-vs-macros.html
Tried with Visual C++, both unsafe() and unsafe(f()) didn't increase i twice. Is there a mistake on the example?
The main idea of #define is that it is just a preprocessor directive, meaning that this:
#define unsafe(i) ( (i) >= 0 ? (i) : -(i) )
will preprocess your code before it is compiled, and will replace the statement
unsafe(x++);
with the following
((x++) >= 0 ? (x++) : -(x++));
Everytime x++ is evaluated, x gets incremented.
One possible reason why you have problems with getting this sample code right might be that you compile your code with optimizations that optimize out all the unused / unnecessary code.
If you don't use your x anywhere, then it is considered as unused, hence does not get included into compiled code.
Just tested the example, Check Eric Gopak's answer for the explanation:
// A macro that returns the absolute value of i
#define unsafe(i) \
((i) >= 0 ? (i) : -(i))
// An inline function that returns the absolute value of i
inline
int safe(int i)
{
return i >= 0 ? i : -i;
}
int countCalls = 0;
int f()
{
return countCalls++;
};
int main()
{
int x = 0;
int ans = 0;
ans = unsafe(x++); // Error! x is incremented twice
ans = unsafe(f()); // Danger! f() is called twice
// x = 2
// countCalls = 2
ans = safe(x++); // Correct! x is incremented once
ans = safe(f()); // Correct! f() is called once
// x = 3
// countCalls = 3
return 0;
}

C++ Can someone explain what these for loops are saying?

So this code is the base outline for a boggle game from online that I copied over.
SOURCE: http://www.codingfriends.com/index.php/2010/06/10/boggle/
bool findUsersWord(string findThis, Grid<char> &theBoard, Vector<cell> &theRoute, string alreadyFound, int placeY, int placeX)
{
// need to find the findThis base case
if (findThis == alreadyFound)
return true;
// need to find the first letter within the board and then progress around that.
if (alreadyFound.empty())
{
for (int rows = 0; rows < theBoard.numRows(); rows++)
for (int cols = 0; cols < theBoard.numCols(); cols++)
// find the each character within the
if (theBoard[rows][cols] == findThis[0])
{
alreadyFound = findThis[0];
cell newR;
newR.row = rows;
newR.col = cols;
theRoute.add(newR);
if (findUsersWord(findThis, theBoard, theRoute, alreadyFound, rows, cols))
return true;
else
// clear out the found Board
theRoute.clear();
}
}
else
{
// try and find the next letters within the area around the base letter
// spin around the letter 3 * 3 grid
for (int y= (placeY > 0 ? placeY-1: placeY); y <=(placeY == (theBoard.numRows()-1) ? placeY : placeY+1);y++)
for (int x=(placeX > 0 ? placeX-1: placeX); x<=(placeX == (theBoard.numCols()-1) ? placeX : placeX+1); x++)
if ((theBoard[y][x] == findThis[alreadyFound.length()]) && (!(y==placeY && x ==placeX)))
// already used letter
if (!placeAlreadyUsed(y,x,theRoute))
{
alreadyFound += findThis[alreadyFound.length()];
cell newR;
newR.row = y;
newR.col = x;
theRoute.add(newR);
if (findUsersWord(findThis, theBoard,theRoute, alreadyFound, y, x))
return true;
else
{
if (alreadyFound.length() > 1)
alreadyFound = alreadyFound.substr(0, alreadyFound.length()-1);
theRoute.removeAt(theRoute.size()-1);
}
}
return false;
}
return false;
}
The code below is the code in question which is part of the code above.
for (int y= (placeY > 0 ? placeY-1: placeY); y <=(placeY == (theBoard.numRows()-1) ? placeY : placeY+1);y++)
for (int x=(placeX > 0 ? placeX-1: placeX); x<=(placeX == (theBoard.numCols()-1) ? placeX : placeX+1)
I am wondering if someone could turn this code into more simple code that doesn't involve the using of ? and that. I do know the simple parts of it such as the "?" means return and ":" means next line, but I am lost in the fact that it is being used in a for loop and the fact that it would just look like
if(placeY > 0)
return playceY-1
placeY;
Where have I gone wrong?
The ? : block is just a strange looking if statement. It's an inline if, if you will.
Here's the format
argument ? result evaluated to if true : result evaluated to if false
Here's an example
1<2 ? "Hurray" : "boo"
Will evaluate to "Hurray" because 1<2 is true. However, if we switch it to 1>2 it will evaluate to "boo".
I do know the simple parts of it such as the "?" means return and ":" means next line
Um, no. That's not what it means at all. ?: is one operator with three operand expressions, one of which appears between the ? and the :.
placeY > 0 ? placeY-1 : placeY
is an expression that means: "If placeY > 0 then evaluate placeY-1; otherwise evaluate placeY".
The idea of the code is that we want, for some reason, to iterate over all positions of the board that are next to (placeX,placeY). Those positions form a rectangle, and the ?: operators are used to compute the left, right, top and bottom limits of that rectangle. For example the expression quoted above is for the top coordinate. It is usually placeY-1, except that if placeY is already 0, there is no row on the board above it, and in that case placeY itself is the top row.