How to make a break point just after loop? - c++

#include <iostream>
#include <vector>
using namespace std;
int in;
bool isPrime(int n) {
for (int i = 3; i <= n; i ++) {
if (n%i != 0) {
return false;
}
}
return true;
}
vector<int>* generateVector(int n) {
vector<int> v;
for (int i = 2; i < 20; i ++) {
if (i == n) {
continue;
}
if (isPrime(i+n)) {
v.push_back(i);
}
}
}
int main()
{
while(1) {
cin >> in;
vector<int>* nVectors[21];
for (int i = 1; i <= 20; i ++) {
nVectors[i] = generateVector(i);
} <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
This some c++ code. And i would like to make a break point just after the for loop(the arrow show the position).
I have found one way to solve it through adding a statement after it then make break point in this statement. But adding a statement without a meaning make not feeling good. So is there a better solution?
I am using GDB for debugging.
PS: I have already known how to set breakpoint in gdb. My intent is to break after the for loop ends, and display what in nVectors. Thanks.
Sorry for all. It's not the issue about the gdb or debugging skill, but there is a bug in my code. So when i print nVectors, nothing was printed. After fixing it, every method you provides works fine. Thanks.

You can use a assembly break point, just need to understand the assembly code of for loop.
gdb <your_bin>
layout split
break *0x80488ad #assmebly code will look like
#0x80488ad jmp 0x8048874 <main+18>

gdb has a command to add break points
there are a couple of ways, but I think the one that might help you is :
(gdb) break filename:linenumber
so for example I want to break at line 10 in main.c
break main.c:10
you might want try a tutorial http://www.yolinux.com/TUTORIALS/GDB-Commands.html

Nope there has to be some statement for the debugger to be able to set breakpoint.

I don't think there is a way to directly do what you want but you can still do it. Set a breakpoint on the last statement of the loop. When the debugger breaks switch the disassembly view and scroll down until you find where you want to place the real breakpoint. This will effective set a breakpoint at a specific address rather than on a line number in a source file.

You can specify the source file and line of the end of the loop, like so, on the gdb command line:
b file.c:123
If you want to go right after the for loop, you'll want to actually set the break for the line of the closing bracket of the while() loop, I believe. But you can try both and see what gives the desired result.

Try to use until command. It is useful to avoid single stepping through a loop. Also from gdb manual:
until always stops your program if it attempts to exit the current
stack frame.

If it was me, I'd set an assembly breakpoint, like the others said. But if you don't want to get into that, there's a simpler way: Since you know the loop count (20), and it is not very big, you can set a breakpoint on the last statement inside the loop (in your case, the only statement inside the loop), with the condition
if (i == 19)
Alternatively, you can set an ignore count:
ignore bnum 19
where bnum is the breakpoint number. This is probably faster, but in your case the difference will be negligible.
See Breakpoints, watchpoints, and catchpoints in the gdb documentation for more information.

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 the Break keyword the most efficent way to exit a for loop? C/C++

Is break the most efficient way to exit a loop? In the code snippet below, would line A or line B be the more efficient way to exit the loop? Any links to material on how the break instruction works under the hood would be appreciated.
for (int i = 0; i < 10; i++) {
cout << i << endl;
if (i == 3) {
break; // A
i = 15; // B
}
}
I assume the difference is trivial in most situations, and that A is faster because B requires an assignment, an increment, and then a comparison, but I don't actually know how break works and it's better to know than assume. Thanks!
Let's compile the following code and look at the assembly:
#include <stdio.h>
int loop_with_break() {
for (int i = 0; i < 10; i ++) {
puts("Hello, world!");
if (i == 3) {
break;
}
}
}
int loop_with_assignment() {
for (int i = 0; i < 10; i ++) {
puts("Hello, world!");
if (i == 3) {
i = 10;
}
}
}
int main() {
loop_with_break();
loop_with_assignment();
}
As you can see, when you use break, if i == 3, it'll jump straight out of the loop to the end of the function, whereas if you use i = 10, it'll set i to 10, increment it by 1, then do the comparison, which is slower. However, this was compiled with no optimizations. If you use optimizations, they both end up becoming the same thing. However, since break is more readable and these optimizations are not guaranteed, you should use it for breaking out of loops.
The keyword break will just quit the loop without any comparison made in the loop condition. If you use i = 15 syntax, the loop will iterate next time to verify whether the variable i is greater than 10, if so, then quit.
In short words, break will break the loop without thinking anything, whereas i = 15 will lead one more iteration to look if the condition satisfies it.
You're right! Actually break keyword is very faster for breaking loop!
In your example, if you use line A, then as soon as control reaches this statement, it will immediately break the loop.
On the other hand, if you use line B, then first the assignment will be performed and again the control will go to the condition checking and when the condition will get false then it will exit from the loop!
if you choose while loop you can prefer to make condition false in the while loop. But in this case using break make sense.

How would the if/else-if statement handle this?

I was just wondering about something that popped into my mind while writing some code.
for (int i = 0; i < num_bits; i++) {
if (bits.at(i) == 0) {
}
else if (bits.at(i) == 1) {
}
}
In this code, bits is a string and num_bits is the length of the string.
In this case, would the program run string.at(i) at both the if and the `else if``, or would it run it once and then store it somewhere and use it at both of the statements? I don't know if the question was clear enough, but thanks for any answer.
Think about it. How would the engine know that every call to that function would produce the same result?
It wil run the function whenever you call it, so for this example 2 times. You can declare it at the top of the for loop or use a foreach if you need to do more heavy operations.

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

Conditional breakpoint modifier to see if array has changed

I was playing with the variable changes breakpoint modifier in Visual Studio 2012. From my understanding, the variable change modifier causes the debugger to break if the specified variable value changes from a previous location execution. I think that this would be useful in narrowing down memory overwrites. My very simple C++ code is this:
int main ()
{
printf("This program converts upper case chars to lower and vice versa\n");
char str[20]="lowercase";;
int i;
for (i=0; i < strlen(str); i++)
{
if (str[i]>=97 && str[i]<=122)
{
str[i]-=32;
}
else
{
str[i]+=32;
}
}
str[1] = 'o';
printf("%s\n",str);
system("PAUSE");
}
Now I set conditional breakpoint on two lines
str[i]=str[i]-32
printf("%s\n", str)
to hit when array str changes. To do this I set a location breakpoint, then select "condition" on right clicking and in the condition textbox I put str,20. Finally I select the "has changed" radio button.
Now what I'm seeing is this:
The breakpoint is hit everytime on the line str[i]-=32, but never on the line printf("%s\n", str) and I'm curious as to why. Obviously the array has changed because of the line preceding the printf statement, so why isn't the breakpoint hit?
What am I missing here?
You are only breaking when that memory is written, not read. The function printf only reads that memory.