sense of if - how is it possible that works - c++

I'm watching Mojam (live games programming, on HumbleBundle) and I saw this piece of code there
(here is screenshot of code)
I'm wondering how come the condition expression in last if statement (which is !wasmoving && ismoving) ever evaluates to true (it does, programmer compiled it and animation was running).
I've tried this in my compiler
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
bool ismoving=5>0;
bool wasmoving=ismoving;
cout << "ismoving"<< ismoving << " oraz wasmoving " << wasmoving << endl;
if (!wasmoving && ismoving) cout << "1st = true 2nd = true" << endl;
system("PAUSE");
return 0;
}
and of course if the last if takes false path, nothing happens.
Could anyone explain how it's posssible that code from screenshot worked?

Note that in the screenshot, the ismoving variable is updated after it is copied to wasmoving, so it is perfectly possible that the value of ismoving is different from the value of wasmoving by the time the condition is evaluated.

Your transformation of the code from the screenshot is inaccurate. You have changed the order of the operations.
C++ and Java, like most mainstream programming languages, are "imperative" languages. This means that programs consist of sequences of instructions that are performed one after another. When that code does:
boolean wasJumping = isJumping;
isJumping = ...someCalculation...;
That first sets the value of wasJumping to be the current value of isJumping, then changes the value of isJumping to something else. wasJumping doesn't change - it still has the old value that was taken from isJumping.
If you come from a mathematical background this can be confusing. I find it helps to read "wasJumping = isJumping" as "wasJumping becomes equal to isJumping", not "wasJumping equals isJumping". The former reinforces that it's describes a change in a variable, rather than describing a permanent relationship between two values.

Related

C++: Why/How a Break Statement Works In This Code?

I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach.
The probelem: "Write a function to check whether a number is prime"
My Approach:
-> I wanted to implement it on my own so I didn't want to copy paste code online where others have used functions with return type bool.
-> Here is the final version of my code that works:
void prime(int k){
for(int k1=2;k1<k;k++){
if(k%k1==0){
cout<<"int is not prime"<<endl;
break;
}
else{
cout<<"int is prime"<<endl;
break;
}
}
}
->I would then call this in int Main() and get the user to input integers and so on.
-> The above code was due to many trial-and-errors on my part and my thought process was as follows: 1)if i don't include the "break;" statement my code results in an infinite loop 2)I needed a way to stop my code from going toward an infinite loop 3) I remember a topic covered in the functions segment of this website , where we can use it to terminate a loop at will. Thats why i incorporated it into my code to produce the final version
My Question:
Can someone explain how the break; statement is working in the context of my code? I know it produces my desired effect but I still haven't gotten an intuition as to how this would do my work.
Many online resources just cite the break statement as something that does so and so and then gives examples. Without going through the code mechanics. Like how a loop would be going through its conditions and then when it encounters the break; statement what does it do? and as a consequence of that what does it do to help my code?
Any advice would be helpful. I still couldn't wrap my head around this the first time I encountered it.
In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop.
So, either of the break statements leads to the loop termination on the first iteration here. If you test for whether a number is being a prime, it does not work.
In essence, you don't need either of the break statements here. They are mostly forced here. Take a look at the following approach:
#include <iostream>
#include <cmath>
bool prime(unsigned k){
if (k != 2) { // Direct check, so to remain similar to the OP's structure of the code
unsigned up_to = sqrt(k) + 1; // Calculate the limit up to which to check
for (unsigned i = 2; i < up_to; ++i) {
if (k % i == 0) {
std::cout << "Is not prime" << std::endl;
return false;
}
else std::cout << "Checking..." << std::endl;
}
}
std::cout << "Is prime" << std::endl;
return true;
}
// Note, we can check just up to the square root of a k
A note on the behavior of the break
The fact that it breaks out the the closest loop to it - has crucial nature for nested loops (all of them: for, while, and do while):
while (/* condition 1 */) // Outer loop
while (/* condition 2 */) // Inner loop
if (/* condition 3 */) break;
Here if the condition 3 is satisfied, the break will lead to break out of the Inner loop but the Outer loop will still continue to iterate.
For more, you may be interested in "How to exit nested loops?" thread. It addresses your second question.
Analogy... I found it in the last place I looked... like always!
Looking for your keys is the LOOP you are in... when you find them... you BREAK out and move on to another task... like maybe getting into your car...
SO if you are IN your car and know your car is where you left your keys... then you are in the PROCESS of getting prepared to drive away... BUT that process requires keys... THUS you change modes/focus and begin a cyclic process of looking for keys... when found to BREAK that searching process IMMEDIATLY and resume what your were doing.
MANY people would make use of the RETURN instrucion in your code pattern... in place of the break! Both do the same thing... however the RETURN is more descriptive english... and one should be concerned with the programmer behind him... Also a bit of digging might show how one is more efficient than the other...

Is there a compiler difference between an if-check and inline conditional?

I've recently begun using flags to handle an input loop's validity condition so it can be checked elsewhere inside the loop rather than having to redo the same check multiple times. However, I'm unsure how best to assign the flag. Is there a generally standard practice regarding this, or just personal style? What, differences are there in the compiled code, if any?
For example, instead of the following code:
bool isValidSize;
do {
std::cout << "Enter the font size (8-12): ";
std::cin >> fontSize;
if (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE) {
isValidSize = true;
} else {
isValidSize = false;
std::cout << "Invalid size. ";
}
} while (!isValidSize);
the if-statement can be changed to make it more clear what isValidSize is set to at a glance:
isValidSize = (fontSize >= MIN_FONT_SIZE && fontSize <= MAX_FONT_SIZE);
if (!isValidSize) {
std::cout << "Invalid size. ";
}
Would this be compiled as an extra if-check? Is there any portability benefit to having the assignment separate from anything else? From just looking at the code, it seems the benefit of the first way is possibly only one branch but an additional assignment per rep and also has an else?
There are no differences: proof.
Tested on GCC 6.3 with optimisations (-O3).
Go for what you think is the more readable one.

Simple if statement not evaluating to true when it should

if ((!m_pMediaPage->PageLayer() || !m_pMediaPage->LoadState()) &&
!m_pMediaPage->m_bRequestList)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
GetListInfo() does not get executed when all values are 0.
PageLayer() and LoadState() return ints and m_bRequestList is an int.
Basically rewritten as this:
if ((!0 || !0) && !0) -or- if ((1 || 1) && 1)
I can only assume that the values being evaluated by the if statement aren't really as seen by the debugger.
I am using visual studio 2005 and put breakpoints on line 1 & 4 to examine the values and see if it executes into the if statement. I am not sure how else to debug this.
Like I said, each of the 3 values are 0 as viewed by the debugger when at breakpoint 1.
Functions in .h:
int PageLayer() {return m_iCurrentLayer;} - protected
BOOL LoadState() {return m_bLoadDone;} - protected
BOOL:
typedef int BOOL;
This conditional statement looks as if it would be executed if all values return from the different functions return zero. If the body of the function isn't executed, I would debug the problem as follows:
Log the values of all functions prior to the if-statement:
std::cout << "page-layer=" << !m_pMediaPage->PageLayer() << ' '
<< "load-state=" << !m_pMediaPage->LoadState() << ' '
<< "request-list=" << !m_pMediaPage->m_bRequestList << '\n';
Yes, the debugger should show these values as well but I have great faith in the values being printed to be the values actually evaluated.
If that doesn't give the necessary insight into what goes wrong, I would start breaking down the condition into separate parts and verify success at each level, e.g.:
if (!m_pMediaPage->PageLAyer()) {
std::cout << "page-layer is not set\n";\
}
if (!m_pMediaPAge->LoadState()) {
std::cout << "load-state is not set\n";
...
If this still doesn't give any insight, I'd start suspecting that the functions return funny values and I would verify that the different results are funny values and I would start looking at the output after preprocesing using the -E option.
You tagged the question as VS2005; do you have all relevant service packs installed to ensure you aren't running into some long-fixed compiler issue?
Secondly, the functions you've listed appear to be very simple setters (you might want to make them const, although that is unrelated to your problem).
You're stepping thru with the debugger, it might therefore be valuable to check your assertion that they are all zero:
bool plCond = (m_pMediaPage->PageLayer());
bool lsCond = (m_pMediaPage->LoadState());
bool rlCond = (m_pMediaPage->m_bRequestList);
bool getListInfoCond = ((!cond1 || !cond2) && !cond3);
if (getListInfoCond)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
If this fixes the problem, you either have a heisenbug or a stack/memory stomp.
If this doesn't fix the problem, it may home in on the cause.
If this DOES fix the problem, you may want to consult the assembly for the code and see if you have somehow tripped a compiler bug.

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}

Memoization Recursion C++

I was implementing a recursive function with memoization for speed ups. The point of the program is as follows:
I shuffle a deck of cards (with an equal number of red and black
cards) and start dealing them face up.
After any card you can say “stop”, at which point I pay you $1 for
every red card dealt and you pay me $1 for every black card dealt.
What is your optimal strategy, and how much would you pay to play
this game?
My recursive function is as follows:
double Game::Value_of_game(double number_of_red_cards, double number_of_black_cards)
{
double value, key;
if(number_of_red_cards == 0)
{
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), number_of_black_cards));
return number_of_black_cards;
}
else if(number_of_black_cards == 0)
{
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), 0));
return 0;
}
card_iter = Card_values.find(Key_hash_table(number_of_red_cards, number_of_black_cards));
if(card_iter != Card_values.end())
{
cout << endl << "Debug: [" << number_of_red_cards << ", " << number_of_black_cards << "] and value = " << card_iter->second << endl;
return card_iter->second;
}
else
{
number_of_total_cards = number_of_red_cards + number_of_black_cards;
prob_red_card = number_of_red_cards/number_of_total_cards;
prob_black_card = number_of_black_cards/number_of_total_cards;
value = max(((prob_red_card*Value_of_game(number_of_red_cards - 1, number_of_black_cards)) +
(prob_black_card*Value_of_game(number_of_red_cards, number_of_black_cards - 1))),
(number_of_black_cards - number_of_red_cards));
cout << "Check: value = " << value << endl;
Card_values.insert(Card_values.begin(), pair<double, double> (Key_hash_table(number_of_red_cards, number_of_black_cards), value));
card_iter = Card_values.find(Key_hash_table(number_of_red_cards , number_of_black_cards ));
if(card_iter != Card_values.end());
return card_iter->second;
}
}
double Game::Key_hash_table(double number_of_red_cards, double number_of_black_cards)
{
double key = number_of_red_cards + (number_of_black_cards*91);
return key;
}
The third if statement is the "memoization" part of the code, it stores all the necessary values. The values that are kept in the map can be thought of as a matrix, these values will correspond to a certain #red cards and #black cards. What is really werid is that when I execute the code for 8 cards in total (4 blacks and 4 reds), I get an incorrect answer. But when I execute the code for 10 cards, my answer is wrong, but now my answer for 4 blacks and 4 reds are correct (8 cards)! Same can be said for 12 cards, where I get the wrong answer for 12 cards, but the correct answer for 10 cards, so on and so forth. There is some bug in the code, however, I can't figure it out.
Nobody actually answered this question with an answer. So I will give it a try, though nneonneo actually put his or her finger on the likely source of your problem.
The first problem that's probably not actually a problem in this case, but sticks out like a sore thumb... you are using double to hold a value that you mostly treat as an integer. In this case, on most systems, this is probably OK. But as a general practice, it is very bad. In particular because you check if a double is exactly equal to 0. It probably will be as, on most systems, with most compilers, a double can hold integers values up to a fairly large size with perfect precision as long as you restrict yourself to adding, subtracting and multiplying by other integers or doubles masquerading as integers to get a new value.
But, that's likely not the source of the error you're seeing, it's just trips every good programmer's alarm bells for smelly code. It should be fixed. The only time you really need them to be doubles is when you're calculating the relative probability of red or black.
And that brings me to the thing that probably is your problem. You have these two statements in your code:
number_of_total_cards = number_of_red_cards + number_of_black_cards;
prob_red_card = number_of_red_cards/number_of_total_cards;
prob_black_card = number_of_black_cards/number_of_total_cards;
which, of course, should read:
number_of_total_cards = number_of_red_cards + number_of_black_cards;
prob_red_card = number_of_red_cards/double(number_of_total_cards);
prob_black_card = number_of_black_cards/double(number_of_total_cards);
because you've been a good programmer and declared those variables as integers.
Presumably prob_red_card and prob_black_card are variables of type double. But they are not declared anywhere in the code you show us. This means that no matter where they are declared, or what their types are, they must be effectively shared by all sub-calls in the recursive call tree for Game::Value_of_game.
The is almost certainly not what you want. It makes it extremely difficult to reason about what values those variables have and what those values represent during any given call in the recursive call tree for your function. They really have to be local variables in order for the algorithm to be tractable to analyze. Luckily, they seem to only be used within the else clause of a particular if statement. So they can be declared when they are initially assigned values. Here is probably what this code should read:
unsigned const int number_of_total_cards = number_of_red_cards + number_of_black_cards;
const double prob_red_card = number_of_red_cards/double(number_of_total_cards);
const double prob_black_card = number_of_black_cards/double(number_of_total_cards);
Note that I also declare them const. It is good practice to declare any variable who's value you don't expect to change during the lifetime of the variable as const. It helps you write code that is more correct by asking the compiler to tell you when you accidentally write code that is incorrect. It also can help the compiler generate better code, though in this case even a trivial analysis of the code reveals that they are not modified during their lifetimes and can be treated as const, so most decent optimizers will essentially put the const in for you for the purposes of code optimization, though that still will not give you the benefit of having the compiler tell you if you accidentally use them in a non-const way.