Why is 16 printed instead of 17 and the variable not incremented? - c++

#include<iostream.h>
void main()
{
int A=5,B=10;
for(int I=1;I<=2;I++)
{
cout<<"Line1="<<A++<<"&"<<B-2<<endl;
cout<<"Line2="<<++B<<"&"<<A+B<<endl;
}
}
The output of this program is
Line1=5&8
Line2=11&16
Line1=6&9
Line2=12&18
I thought that it will produce 17 and 19 in place of the 16 and 18 in the second and fourth lines of the output. This is because, in the first run of the loop, first the value of A is 5 and the first command prints 5&8 and should increment the value of A by 1, making it 6. In the second command it should print 11&(6+11) which should print 11&17 but the output is not that.
Where is the loophole in my reasoning??

Im not an expert on the subject, but I believe it is because of the order of operations that are performed in the background.
Mainly "<<" is something called an overloaded operator, which basicly means that someone, somewhere wrote what it should do, and how to do it.
And if you have a bunch of things written one after the other, like you have:
cout<<"Line2="<<++B<<"&"<<A+B<<endl;
The compiler has to do some fancy tricks to make it work.
The way the program runs through such code, is from right to left.
So in essence it kinda runs in reverse to the way you would think it does.
First it pushes endl, then it does A+B and pushes it, then it pushes &, then it increments B and it also pushes it, finaly it pushes Line2= forming the complete "sentence". These are then taken to the console (or whatever else you might have) to be printed to your screen at once.
As a solution to the issue, try separating cout into 2 lines; something like this:
cout <<"Line2="<<++B<<"&";
cout <<A+B<<endl;
Or ,if allowed to, try swaping ++B and A+B, this should also solve the issue, however your results will also be reversed.
cout<<"Line2="<<A+B<<"&"<<++B<<endl;
tl;dr: A+B happendes before B++, doing them in spearate lines or swaping the positions should solve the problem

Related

`ncurses` function `wgetstr` is modifying my variables

SOLUTION Apparently, the wgetstr function does not make a new buffer. If the second argument is called data and has size n and you give an input of more than n characters, it will access and overwrite parts in memory that do not belong to data, such as the place in memory where cursorY is stored. To make everything work, I declared data with char data[] = " "; (eight spaces) and wrote wgetnstr(inputWin, data, 8);.
--------------------------------------------------------------------------------------------------------------
It seems that the ncurses function wgetstr is literally changing the values of my variables. In a function called playGame, I have a variable called cursorY (of type int) which is adjusted whenever I press the up- or down-arrow on my keyboard (this works fine).
Please take a look at this code (inputWin is of type WINDOW*):
mvprintw(0, 0, (to_string(cursorY)).c_str());
refresh();
usleep(500000);
wgetstr(inputWin, data);
mvprintw(0, 0, (to_string(cursorY)).c_str());
refresh();
usleep(500000);
Suppose I move the cursor to the 6th row and then press Enter (which causes this piece of code to be executed). There are two things I can do:
Input just 1 character. After both refresh calls, the value 6 is shown on the screen (at position (0, 0)).
Input 2 or more characters. In this case, after the first refresh call I simply get 6, but after the second, I magically get 0.
The first two lines after the code above are
noecho();
_theView -> _theActualSheet -> putData(cursorY-1, cursorX/9 - 1, data);
(don't worry about the acutal parameters: the math regarding them checks out). While I'm in putData, I get a Segmentation fault, and gdb says that the first argument of putData was -1, so then cursorY had to be 0 (the first two arguments of putData are used to access a two-dimensional array using SheetCells[row][column], where row and column are, respectively, the first and second formal parameter of putData).
Clearly, wgetstr modifies the value of cursorY. The name of the latter variable doesn't matter: changing it to cursorrY or something weird like monkeyBusiness (yes I've tried that) doesn't work. What sort of works is replacing the piece of code above with
mvprintw(0, 0, (to_string(cursorY)).c_str());
refresh();
usleep(500000);
int a = cursorY;
wgetstr(inputWin, data);
cursorY = a;
mvprintw(0, 0, (to_string(cursorY)).c_str());
refresh();
usleep(500000);
In both cases I see 6 at the top-left corner of my screen. However, know the string is acting all weird: when I type in asdf as my string, then move to the right (i.e., I press the right key on my keyboard), then type in asdf again, I get as^a.
So basically, I would like to know two things:
Why the HELL is wgetstr changing my variables?
Why is it only happening when I input more than 1 character?
What seems to be wrong with wgetstr in general? It seems terrible at handling input.
I could try other things (like manually reading in characters and then concatenating data with them), but wgetstr seems perfect for what I want to do, and there is no reason I should switch here.
Any help is much appreciated. (Keep in mind: I specifically want to know why the value of cursorY is being changed. If you would recommend not using wgetstr and have a good alternative, please tell me, but I'm most interested in knowing why cursorY is being altered.)
EDIT The variable data is of type char[] and declared like so: char data[] = "". I don't "clear" this variable (i.e., remove all "letters"), but I don't think this makes any difference, as I think wgetstr just overrides the whole variable (or am I terribly wrong here?).
The buffer you provide for the data, data, is defined as being a single character long (only the null-terminator will be there). This means that if you enter any input of one or more characters, you will be writing outside the space provided by data, and thus overwrite something else. It looks like cursorY is the lucky variable that got hit.
You need to make sure that data is at least big enough to handle all inputs. And preferably, you should switch to some input function (like wgetnstr) that will let you pass the size of the buffer, otherwise it will always be possible to crash your application by typing enough characters.
wgetstr expects to write the received characters to a preallocated buffer, which should be at least as long as the expected input string. It does not allocate a new buffer for you!
What you've done is provide it with a single byte buffer, and are writing multiple bytes to it. This will stomp over the other variables you've defined in your function after data, such as cursorY, regardless of what it is called. Any changes to variables will in turn change the string that was read in:
int a = cursorY;
wgetstr(inputWin, data);
cursorY = a;
will write an int value into your string, which is why it is apparently getting corrupted.
What you should actually do is to make data actually long enough for the anticipated input, and ideally use something like wgetnstr to ensure you don't walk off the end of the buffer and cause damage.

Can a main() return before all cout has been written to the consol?

I try to track down an error in a R-script that does call a C++ program. The R tells me, that my C++ returned NA - but that does not seems to be the case when I look through the program. There is nothing called that would result in NA in R. Hence my question, if R may never capture the output from the C++ program, because return 0 is called before all output has been written to the console.
My program does writes some numbers to the console. One number per line, the last line ends with endl.
main()
{
cout<<33.12<<"\n"; //print a couple of number to cout
cout<<9711.3<<"\n"<<5699.14<<endl;
return 0;
}
My R-Script does stuff like this:
x <- as.numeric(system("./myProgram", intern=T))
if(any(is.na(x))) {
stop("Wooppp, x is NA: ", x)
}
Can it be, that R does not get the cout-output from by program?
This question is related to the corresponding R-question:
DEOptim keeps telling: NaN value of objective function
In general, yes, it would be possible to have part of the output not yet flushed before the end of main(). However, by the end of the program, everything should be flushed anyhow.
Some more detail, main is just a function, for the programmer this is the entry point of the program, though actually the runtime does some parts before/after this call. This includes loading shared objects, calling destructors of global variables and some other stuff you actually shouldn't know anything about as a regular programmer.
As std::cout is a global object, it will use its destructor to flush the right data. Though as most implementations flush on the "\n" character (don't think it is needed), std::endl and std::flush (I thought this was required), this example should be fine anyhow.
I would try splitting this issue, and try pushing the output of the C++ program to file to read it afterwards (both from the same R-program), try console input ...

C++ if/else grid system

I am trying to create a C++ program that will move an X on a 4x4 grid and display each move. We are not allowed to use arrays because we haven't learned how yet. I know that I am supposed to use 16 if/else statements, but I am not sure what to do from there. I know there is an easier way than mapping out each possible option because that would take forever!!! What do I do???
EDIT: It is only allowed to move up/down/left/right. And what I mean by display each move it is first supposed to display the user's starting point (which I've already set up) and then it is supposed to print grids with successive moves on them including all of the previous moves until it reaches the end point.
Note: I originally wrote this answer based on assumptions about the task that turned out to be wrong. However, I'll leave the answer up as I believe it might still contain useful information for the OP.
When you have x different possible situations, you don't always need an if/else with x branches. The trick is to find a way to use the same computation (typically one or more mathematical expressions, and possibly loops) to handle all or most of the situations.
In this case, there are indeed 16 different positions on a 4x4 grid, and one way to represent a position is to store its row and column number (each a value between 0 and 3). By using two loops, one inside the other (nested loops), you can generate all 16 combinations of row and column position. I'll assume now that you're supposed to print e.g. . on the empty cells of the grid. Inside the inner loop, you need to figure out whether you should print a . or an X. What question should you ask in order to figure that out? Simply "is the row and column number that the nested loops are currently at the same row and column number as the location of the X?"
Edit after seeing your update: Even when working with a grid, arrays are only needed when you have to store information about every cell, so one can sometimes get away without an array if you can generate the grid information from fewer pieces of information (such as the position of the X). However, if you need to keep track of the previous positions, you need an array (either one- or two-dimensional) in order to do it elegantly. I would say that the "no arrays" restriction of this task is not educational, as it forces an unnatural and very cumbersome way to solve this task. :-( (However, if your instructor subsequently gives the same task and allows you to use loops, it will be a good demonstration of why loops are useful.)
What you could do is to use 16 bool variables (all set to false initially) with names such as grid00, grid01, grid02, grid03, grid10, ..., grid33. Then make two methods, bool isOccupied(int row, int column) and void occupy(int row, int column) that use 16-way if/else statements to allow you to easily read and change the variable that corresponds to a given position.
I know that I am supposed to use 16 if/else statements, but I am not
sure what to do from there.
If this is a constraint on your solution given to your by your instructor, that means that you will need to handle each of the 16 possible grid locations in a separate {} block. You'll have to have an enum representing each of the pairs. like:
e_1_1, e_1_2, e_1_3, e_1_4,
e_2_1, e_2_2, e_2_3, e_2_4,
e_3_1, e_3_2, e_3_3, e_3_4,
e_4_1, e_4_2, e_4_3, e_4_4,
and you'll have to manually update the current position to a new one in the switch statement. Keep track of your current position in a variable called something like 'position'.
I know there is an easier way than mapping out each possible option
because that would take forever!!!
Welcome to programming. ;-)
Copy and paste is your friend and this problem of having to write a lot of similar but slightly different code is fairly common to many programming tasks. Becoming a good programmer means learning how to avoid largely duplicate code when possible. You are not there yet, or you wouldn't have to ask. So this first step will be an important lesson for you. A bit of pain will help you appreciate how much better the approach you will use the next time will be.
But this isn't that much work. An experienced C++ programmer could knock this out in less than 5 to 10 minutes. Moderately experienced, perhaps 20 to 30. It might take a learning programmer a few hours or more.
There are more concise ways to handle this problem without requiring 16 separate blocks, however, none of them are easier to understand. If this a requirement for a class learning project, then you will find it beneficial to do it first this way, then as a next step, try to do it with more complex logic.
Suggestions
An experienced programmer would define the move possibilities as an enum. Then the moves would be handled inside the {} blocks for the if statements using a switch statement that handled each of the four enums corresponding to the four moves. If you don't know the switch statement yet you can use an if ... else if ... else if ... that checks for each of the four moves.
Start with handling just the first upper left corner position moves for a smaller 2 x 2 grid. Then add each of the other three positions for the 2 x 2 grid. Once you have that working you should be able to understand easily how to extend the solution to a 4 x 4 and arbitrarily larger grid.
You'll want to have a function that prints the position array that gets called after every move. For now, you'll have to check the value of the enum and print manually. Something like:
Is position == e_1_1? print '* else print '_'
Is position == e_1_2? print '* else print '_'
Is position == e_1_3? print '* else print '_'
Is position == e_1_4? print '* else print '_'
print a newline
Is position == e_2_1? print '* else print '_'
Is position == e_2_2? print '* else print '_'
Is position == e_2_3? print '* else print '_'
Is position == e_2_4? print '* else print '_'
etc.
Some pointers for easy debugging:
Set the values for an enum for up, down, left, and right to something you can print out and follow easily, i.e. e_up = 'u' and e_down = 'd'. That will make it easier to debug if you don't have an IDE that will let you easily see the enum values, and you can print out the moves directly in the beginning.
Make your changes to the code in small increments. Run the code and once you know that the part you added works, move on. If you add too much at once it is much harder to figure out where things are broken, especially when you are new.
Future Solution with Arrays
Some hints: You'll want to use a two-dimensional array.
Try this on a 2 x 2 array first to make your life simpler. Then when the logic works, change the array size. To make this process easier use a const integer to define a value that you use to define the arrays and the printing using a for loop so that when you change the constant from:
const int array_size = 2
to
const int array_size = 4
the rest of the code will just work. For extra credit, support arrays of differing height and width by using separate constants for array_height and array_width. Learn to do it well and the way a pro would do it and you'll develop pro habits and earn pro wages much more quickly.
Remember to use a for loop for printing the rows and columns that uses the constants you defined.
You'll want to have the code running a loop looking for input, then processing the move, then printing out the new grid.

What's the difference between these 2 'if' and 'if-else' statements?

What is the difference between 2 if statements and 1 if-else statement?
int x;
cin >> x;
if (x==10)
cout << "Hello";
if (x!=10)
cout << "Hey";
int x;
cin >> x;
if (x==10)
cout << "Hello";
else
cout << "Hey";
In practice, the optimizer will probably make them exactly the same. The best thing to do in these cases is to try it - look at the assembly output of your compiler, and you'll see exactly what the difference is.
The difference is that in the second case the condition is checked and computed only once.
In the first example both are evaluated, always.
In the second example if first is true, it never gets to second.
The most important difference (to my mind) is that the first form is harder to read and is more error-prone.
The second form reads more like English: "If x is 10 then do this, else do that" whereas the first form essentially makes the two clauses unrelated. It's error prone because if you decide that the threshold 10 needs to change then you need to update it in two places rather than just one.
In terms of execution speed, I'd be very surprised if there is any difference at all. There will be two evaluations with the first form but that's the least of the problems. It's certainly not the sort of thing you should waste time optimising.
There is no visible output difference. However, it does make your code easier to read if you use the ladder one
if (x==10) //matches only if x is number 10 , then processor jump to next line i.e.
if (x!=10) // matches only if x is not number 10
where as
other if checked only , if the number is either 10 or anything else then 10.
In a way both will result same, but its just matter of statements.
so
in first example, both lines of if will be executed
in second example either of one is executed
So its better to use second one for performance
From a maintainability point of view the first one
violates the DRY principle.
is a lot harder to understand and modify. Not with a trivial condition, like here, but with a nice long condition you'll either have to just cut 'n paste the condition and slap a ! in front, or try to remember how De Morgan's laws were formulated... And some day that will fail, and the inverted if will fail to be the exact opposite of the first....
So, else is the way to go.
In the first block both if statement will run by the compiler...
But int the second one only 1 statement will run as both are linked with a single condition . Either if can be true or else can be true
You can understand this as considering 1st one as 'and' type
And the 2nd one as 'or' type

printing using one '\n'

I am pretty sure all of you are familiar with the concept of the Big4, and I have several stuffs to do print in each of the constructor, assignment, destructor, and copy constructor.
The restriction is this:
I CAN'T use more than one newline (e.g., ƒn or std::endl) in any method
I can have a method called print, so I am guessing print is where I will put that precious one and only '\n', my problem is that how can the method print which prints different things on each of the element I want to print in each of the Big4? Any idea? Maybe overloading the Big4?
Maybe I don't understand the question completely because it is asked rather awkwardly, but can't you just have a function called newline that receives an ostream as an argument, and then simply prints '/n' to that output stream? Then you can just call that infinitely many times, while still abiding the arbitrary "one newline" rule.
e.g.
(edit: code removed, "smells like homework")
print should take a parameter containing the information to output to the screen (sans '\n') and then call the c++ output method with in-line appending the '\n' to the passed in information.
note: no code 'cause this smells like homework to me...
I'm not sure I completely understand what you're trying to accomplish. Why is it that you can only use one newline? What makes it difficult to just write your code with only one newline in it? For example, I've done stuff like this before.
for(int i = 0; i < 10; i++) {
cout << i << " ";
}
cout << std::endl;
If you need something more complicated, you might want to make some sort of print tracker object that keeps a flag for whether a newline has been printed, and adjusts its behavior accordingly. This seems like it might be a little overly complicated though.