This is a specific problem, but I can't seem to figure out what is wrong.
else if (X == 2)
//move left
{
if (Level[X-1][Y] == 0);
{
cout << Level[X-1][Y] << "\n";
cout << "\n MOVING LEFT from RIGHT\n"; //PROBLEM IS HERE
Level[X][Y] = 1; // block it
X = X - 1;
moved = 1;
}
}
What I am doing is I am checking if Level[X-1][Y] is 1, indicating a column, so I can not move my player there. However for some reason, despite it being 1 and not 0 (as indicated by the output), the IF statement is still accessed. Any help will be appreciated.
Your problem is here:
if (Level[X-1][Y] == 0);
^
the ; ends the if statement. What follows the if statement is just a compound statement like this:
{
//Code
}
and are completely valid on their own and have many uses, one use of which is creating a block scope.
For completeness sake if we go to the draft C++ standard section 6.2 Expression Statements we see that the ; just terminates a null statement. The grammar is as follows:
expression-statement:
expressionopt ;
^
and it also says:
[...]An expression statement with the expression missing is called a null statement.[...]
Semi-colon!!!
if (Level[X-1][Y] == 0);
if (Level[X-1][Y] == 0);
// ^
Get rid of this semicolon.
It would make the logic like this: if Level[X-1][Y] is zero, do nothing, then run the following code(the compound statement you thought was belong to the if). It's equivalent to:
if (Level[X-1][Y] == 0)
{
;
}
{
cout << Level[X-1][Y] << "\n";
cout << "\n MOVING LEFT from RIGHT\n";
Level[X][Y] = 1;
X = X - 1;
moved = 1;
}
Related
Consider:
for(int i = 10; b >= i; i++){
if(i%2 == 0)
cout << "even" << endl;
else
cout << "odd" << endl;
}
for(int i = 10; b >= i; i++){
if(i%2 == 0){
cout << "even" << endl;
}else{
cout << "odd" << endl;
}
}
Both of these code work with the only difference being the curly brackets for the if else statement. When should I use curly brackets and when not?
They're called braces or curly brackets, not to be confused with the "curly arrow" in some languages, ~>.
In C, and by inheritance C++, these are optional on single-line if statements, but as many, many bugs have been created by omitting them you'd be advised to use them as a matter of principle even when they're redundant.
That is a mistake like this is easy to overlook:
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
Where it seems like that goto is conditional, yet it's not, it just drops through. This is the huge OpenSSL bug that caught everyone by surprise, and if veteran developers can mess it up, so can you.
The second form is the most reliable, least ambiguous, especially when formatted according to typical conventions:
for (int i = 10 ; b >= i;i++) {
if (i%2 == 0) {
cout << "even" << endl;
}
else {
cout << "odd" << endl;
}
}
for is a statement, not a function, so the syntax is for (...) with a space. Functions have no space, like f(...). Omitting the space implies for is a function, which it absolutely is not. The same goes for if, while and so on.
It's worth noting that the original code can actually be reduced to:
for (int i = 10 ; b >= i;i++)
if (i%2 == 0)
cout << "even" << endl;
else
cout << "odd" << endl;
Since that if is a single statement, even with the else clause attached.
Again, this is not advised because the rules of what is and isn't a single statement can be confusing.
Google has a detailed C++ style guide that may help you. In particular, it says that
In general, curly braces are not required for single-line statements, but they are allowed if you like them; conditional or loop statements with complex conditions or statements may be more readable with curly braces. Some projects require that an if must always have an accompanying brace.
If the 'if', 'else' or 'for' structures have only one statement inside them, you can decide not to use the curly brackets. However, I would recommend to use them in order to improve the code readability.
I'm a newbie here and I just started college. We are learning C++ and I find it a little bit difficult, because of the way the teachers explain.
Yesterday we did a task that says to create a program, which finds greatest common divisor of 2 numbers. So, the teacher started writing the code, but the explanation wasn't enough for me and I really need some help right now.
(I putted comments on the things I don't understand.)
Here is the code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a, b;
cout << "a = ";
cin >> a;
cout << "b = ";
cin >> b;
cout << "GCD (" << a << ", " << b << ") is ";
if (a != 0 && b != 0){
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
size_t max = abs(a) > abs(b) ? abs(a) : abs(b);
size_t diff = max - min; //What is that variable used for?
while (diff > 0)
{
min = diff < min ? diff : min;
max = diff > min ? diff : min;
diff = max - min;
}
cout << min << endl;
}
else{
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
}
system("pause");
return 0;
}
QUESTION: When should I put {} on if's, while's etc.?
This is the syntax for an if-statement
if ( condition ) statement-true else statement-false
statement-true is either one statement or a block of statements in {...}
So you can use if without {...} if there is only one line. But it is better to always use {...}.
It is necessary when you need more that one line/statement to be executed by the if/else/while. Valid examples:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) cout << (a>b ? a : b) << endl;
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
a++; }
If you did:
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
a++;
The the a++; would be executed regardless of the if condition.
Some programmers like to use {} even for single statements because they believe it leads to more usable and maintainable code. I do not belong to that group but I can see the arguments on either side.
size_t min = abs(a) < abs(b) ? abs(a) : abs(b); //What's that after (?)?
C and C++ have a construct that is similar to an if-else statement. This line basically says that if abs(a) is smaller than abs(b), then min should take the value of abs(a); otherwise, it should take the value of abs(b).
size_t diff = max - min; //What is that variable used for?
It's not clear what you mean here. If you mean diff, the code essentially uses it in the subsequent while loop to perform division by repeated subtraction. This is a very strange thing to do, especially because it is so inefficient, and division would have been more compact and efficient in the loop. It's even stranger given that earlier the author uses ?: (which you asked about); that construction is used mainly because it's more compact and efficient than an if-else statement, but this is rather strange code, anyway.
When should I put {} on if's, while's etc.?
You should do it by default. You don't have to do it if only one statement is to be performed when the condition is true (resp. false) but people usually do as a matter of good style and to assist readability. For instance, this code
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
else
cout << "not possible!!!\n";
could just as easily be
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
} else {
cout << "not possible!!!\n";
}
...and a lot of instructors would actually require the latter from learners.
In addition to the other answers:
//What's that after (?)?
foo ? bar : qux;
Is the use of the ternary operator.
If foo is true the expression evaluates to bar else it evaluates to qux.
Just adding my two cents...
This
if (a != 0 || b != 0)
cout << (a>b ? a : b) << endl;
is equivalent to
if (a != 0 || b != 0) {
cout << (a>b ? a : b) << endl;
}
The big difference comes when you realize that code is not something static that you write once and then never change again. Lets change the example a little bit (intentially weird intendation)
if ( x ) // (I)
y = a;
z = b;
is not the same as
if ( x ) { // (II)
y = a;
z = b;
}
Using brackets allows you to focus on only the part you care about. Consider that you later decide to swap the two lines, then
if ( x ) {
z = b;
y = a;
}
is still ok (its the same as (II), apart from swapping the two instructions), while
if ( x )
z = b;
y = a;
is doing something completely different as the version above (I). If you use the brackets you dont need to care whether those two lines are inside a if block. To decide if you can swap them you need to look at nothing more than those two lines. This is not the case if you do not use the brackets. This may seem like a minor thing, though I have seen countless bugs caused by not putting brackets where there could be some.
For 1 line of code following if, else, else if, while, etc
if (<some condition>)
//1 line of code`
and
if (<some condition>)
{
//1 line of code
}
...are equivalent and it is up to you (personal style,developer choice,readability etc.) to make that decision.
For > 1 line of code following if, else, else if, while, etc
{} is required if you want code completely scoped to the condition statement. It is up to you the developer to make sure to scope these lines of code (i.e. the compiler will not warn you about this.. it will not know if the intent was 1 line or multiple lines).
So an example
if(<some condition>)
{
//line of code 1
//line of code 2
}
the compiler will let you do this...
if(<some condition>)
// line of code 1
// line of code 2
but //line of code 2 has no relation to the if condition since it was not scoped with {} and will be executed regardless of the if statement condition.
I have this function:
void m(int n)
{
if(n > 0)
m(--n);
cout << n << " "; //for n = 5 --> output is: 0 0 1 2 3 4
}
I have a problem with understanding how it works.
For example:
n(input) = 5
output: 0 0 1 2 3 4
My question is: Why does it show zero twice?
When I add brackets like this:
void m(int n)
{
if(n > 0)
{
m(--n);
cout << n << " "; // now, it shows 0 1 2 3 4 (n = 5)
}
}
So, what brackets cause in this code, that "0" exists only once?
And when I change pre-decrement (--n) to post-decrement (n--) it shows nothing. Why?
Could somebody help me to understand how it works?
First thing to note is : in C++ if you don't put brackets after an if statement, only the next line will be in the statement.
Example :
if(x > 0)
cout << 1;
cout << 2;
Here cout << 2 will always be executed no matter the value of x
The correct way of writing this is
if(x > 0)
{
cout << 1;
cout << 2;
}
Same thing goes for else statements
So this was for the brackets.
My wild guess for the post decrement is the following :
if you do m(n--), the value passed will be 5, the value of n will only change after the function call and go out of scope (so it won't matter). So what will happen is an infinite number of m(5) calls and that's why nothing is appearing. (I'm not sure about that part so please tell me if wrong) !
Hope it helped !
Looks like you confused with Python syntax, where scope of if is determined by indent. In C (and C++, C#, Java an many other languages) the scope is one statement (which ends with ;) unless you use curly brackets { and }. In the 1st variant of your code cout << n << ... will be always performed, regardless of value of n. In second variant it will be performed only if(n > 0)
As I plan to make a small game to test myself on what I know so far in C++, I found that using this is giving me an error at the location of the "else".
Can anyone help?
int lvlup()
{
if (user.xp >= user.maxxp)
user.xp = 0;
user.maxxp + 10;
user.maxhealth += user.maxhealth * .5;
user.defense + 2;
user.attack + 3;
user.lvl + 1;
else
return 0;
};
You need to group statements with {} in c++, and you don't need a ; after the function.
You also have missed the = sign in a few places. I'm assuming user is a global, but it really should be passed in, but I'll leave that up to you.
I'm assuming the return value is whether the user leveled up, so that really should be a bool, not an int. I've added a return statement to the if true block. Depending on the use of lvlup that may or may not make sense. If the return value is not used you shouldn't have any and use void.
So your code should be:
int lvlup()
{
if (user.xp >= user.maxxp)
{
user.xp = 0;
user.maxxp += 10;
user.maxhealth += user.maxhealth * .5;
user.defense += 2;
user.attack += 3;
user.lvl += 1;
return 1;
}
else
return 0;
}
If your if/else statement has only one line you can choose not to have any braces, but if there is more than one line to be executed in response to the conditional you need to include them. However not including them can open up the possibility for someone maintaining the code to make a mistake and not put them in when adding a line to the block, so some people say always add them.
You need some brackets {}.
In fact, the if brunch and the for loop only execute the next line if no brackets found surrounding the piece of code.
example :
a = 1;
if (a == 0)
std::cout << "This line is skipped" << endl;
std::cout << "This line will appear" << endl;
If you execute this code, the output will be:
This line will appear
and if an else is following the if statement, a compilation error is generated which is your case :p
and if you write down some brackets to structure your code like below:
a = 0;
if (a == 0) {
std::cout << "This line is not skipped" << endl;
std::cout << "This line will appear too" << endl;
}
the output will be :
This line is not skipped
This line will appear too
The for loop will only loop the only line next to the for loop if no brackets found too.
I have two snippets:
while (indent-- > 0)
{
out << " ";
}
while (indent > 0)
{
indent -= 1;
out << " ";
}
As far as I can see, there isn't any undefined behaviour going on in the first snippet (see here).
My question is: are these two snippets equivalent?
I am not so sure, because the -= operator has a higher precedence than the compare operator, and should therefore be performed first in the first snippet. The second snippet however, only performs this after comparison.
They will run the body of the loop the same number of times, but they are not the same.
The first will decrement indent one extra time, leaving indent at -1, because the -- operator will run whether the condition succeeds or fails.
The second will leave indent at 0. Here's a complete working example:
#include <iostream>
int main()
{
int indent = 3;
while (indent-- > 0)
{
std::cout << "First "; // Prints three times
}
std::cout << indent << std::endl; // Prints -1
indent = 3;
while (indent > 0)
{
indent -= 1;
std::cout << "Second "; // Prints three times
}
std::cout << indent << std::endl; // Prints 0
}
// Output:
// First First First -1
// Second Second Second 0
There's no difference between the two because indent-- is a post-increment - it will return the previous value of indent - there would be a difference for while (--indent > 0) though.
So, for basic types, they're equivalent.
Since this is C++, though, you can just as well define your own class, have indent an object of that type, overload -- and =(int) and > and have them behave completely different (I hope this isn't the case).
EDIT: correct, the value of indent isn't the same.
I think they are different. What is missing is initialization of indent and its type.
First loop will always decrement after comparison, second only when condition was true. If (indent > 0) is true before loop, they behave exactly the same way. If indent==0 however, first loop will make it -1 without printing it once. Second will not print any indent, but wont decrease indent also.
So, they are different in some cases.