How do I use "goto" in C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
When ı use goto in class in c++ ,I faced to that message,how can ı use goto in class c++?
In member function `void note_system::student_no()':
label 'stop' used but not defined`

You would do something like this (to have a single scope exit point, say when for some exotic reason using a RAII-based trick is not possible):
status_code func_with_goto() {
if (i_see_errors()) goto func_end;
...
func_end:
return status_code::error;
}
Or like this (to emulate break-by-label-like behavior):
outer: while (...) {
inner: while (...) {
...
goto outer;
}
}
Or if you just want to reimplement your second Basic program from 80-th in C++:
x10: std::cout << "Hello World!" << std::endl;
x20: goto x10;
There are very few cases where goto may be justified. Its presence complicates static code analysis by both humans and compilers. This does not mean at all that goto should be banned, it should just be use with double care.

Related

function declaration in pro*C without body [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Based on the comments i ve changed the subject to proc code and i
withdraw the claim that it is C++ syntax. Keeping the tags same; as i
still hope it is similar to c++ and no ProC tag available please bear
with it.
I suppose its a very new bee question. But as i have no ample time to learn C++ documentation i would appreciate if i can get help on this.
I am working on converting pro*C code which resembles C++ syntax.
Here is the code snippet
#include <stdio.h>
#include <string.h>
#include <prg_codes.h>
#include <prg_defines.h>
typedef struct
{
int errorflag;
int slot;
} option_info;
int calc_options(currArgc,currArgv,options)
int currArgc;
char *currArgv[];
option_info *options;
{
int optChar;
int invopt=0;
while ((optChar = getopt(currArgc, currArgv, ":s:")) != -1 && !(invopt))
{}
/* other commands */
}
void main(int argc, char *argv[])
{
option_info options;
int rc = 0;
rc=calc_options(argc,argv,&options);
/* other commands */
}
My question is
option_info is defined as a struct then as a function and called from main. Is it fine? how does it work?
Is option_info inside the function calc_options. Because option_info seems using the parameters defined in calc_options.
Or calc_options body is written somewhere else in any other file in the include section ?
This snippet is in the archaic K&R C syntax which predates ANSI C. Then it is indented strangely which makes it look at first glance like you describe, but it really isn't. calc_options is the function definition with three arguments, the 3rd of which is a pointer options to typedef option_info.
This is the same thing in ANSI C syntax, so it is easier to read:
int calc_options(int currArgc, char *currArgv[], option_info *options)
{
int optChar;
int invopt=0;
while ((optChar = getopt(currArgc, currArgv, ":s:")) != -1 && !(invopt))
{}
/* other commands */
}
"option_info is defined as a struct" Yes (well a typedef to a struct)
"then as a function and called from main". No
"Is it fine?" Yes (but should be changed to ANSI syntax)
"how does it work?" Pretty good
"Is option_info inside the function calc_options?" It is the type of the 3rd argument options
"Because option_info seems using the parameters defined in calc_options." It is the type of parameter options
"Or calc_options body is written somewhere else in any other file in the include section ?" Nope

How to return error code from the main function in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}

C++ store number of times main is called [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
How do I have main() remember the value of a variable each time it is called?
i.e. if I run this program the first time I want mainCallCounter = 0, but when I is called again I want it to increase the counter
#include <iostream>
using namespace std;
static int mainCallCounter = 0;
void outputMainCallCount()
{
cout << "Main was called" << mainCallCounter << "times." << endl;
}
int main()
{
outputMainCallCount();
mainCallCounter++;
return 0;
Main is the entry point for your program. Main is called once (normally) and, when it exits, your program is torn down and cleaned up.
Obviously this means a local variable will be insufficient. You need some sort of external storage which persists longer than your application, i.e., the file system.
You can't. Each run of a program is independent. You will need to save mainCallCounter somewhere and re-read it the next time the application launches. Writing it into a file is one option, another might be something like the Windows registry or Mac OS X defaults system, etc.
All variables declared in C++ expire when the program ends. If you want to persistently remember how many times the program has been run, you will need to store that data in an external file and update it whenever you run the program.
For example:
#include <iostream>
#include <fstream>
int numTimesRun() {
std::ifstream input("counter.txt"); // assuming it exists
int numTimesRun;
input >> numTimesRun;
return numTimesRun;
}
void updateCounter() {
int counter = numTimesRun();
std::ofstream output("counter.txt");
output << counter;
}
int main() {
int timesRun = numTimesRun();
updateCounter();
/* ... */
}
Hope this helps!

Under what circumstances is it feasible to use exception handling? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have seen many exception handling mechanisms where they simply weren't necessary. A lot of the times the problem could have been solved in a much cleaner way using simple if statements.
For example, things like:
Invalid input
Division by zero
Wrong type
Container range check
Null pointer
Uninitialized data
... and so on.
Could someone provide an example where it would be a better approach to handle exceptions?
Exceptions become more important as your program size grows.
With a simple application return codes are probably fine. But when an error condition needs to bubble up a couple levels of the stack before being handled, it starts to make sense to use exceptions instead of passing error codes from every function.
Also, when a method already returns a value, it may not be practical or possible to return an error code from the function as well.
Sometimes using exception is cleaner. In function foo thanks to exception throwing in check function you can avoid checking what check returns what makes this function simpler:
#include<iostream>
using namespace std;
class A{
public:
int a_foo(int index){return _tab[index];}
private:
static int _tab[3];
};
int A::_tab[3]={1,2,3};
void check(int index)
{
if (index < 0 || index > 2)
throw string("invalid index");
}
void foo(A a, int index){
check(index);
cout << a.a_foo(index) << endl;
}
int main()
{
try
{
A a;
foo(a,4);
}
catch(string ex)
{
cerr << ex <<'\n';
}
}
I would use it when the consequence of some unexpected 'event' is inability for application to continue running. When it happens and you catch it, report it nicely and close the application (or whatever you think you should do in that case).

Should I use ELSE IF and ELSE or avoid them when possible? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I often write functions with conditional branches like this:
function f
if(X) {
do something minor;
}
else if(Y) {
do something minor;
}
else {
do a whole lot of stuff;
}
I could achieve the same results doing:
function f
if(X) {
do something minor;
return;
}
if(Y) {
do something minor;
return;
}
do a whole lot of stuff
I like that the second one doesn't require I indent the majority of my code, but am not sure if this is considered good practice or not. Since there's no common code following the conditional it seems justifiable to do a hard return. But the first style seems to have merits also.
Personally I think using lots of return statements can make code less readable
I often layout my code so that the 'main' body of a function doesn't all have to be indented, in your case:
function f
if (X || Y) {
if (X) do something minor;
if (Y) do something minor;
return; // with comment explaining what we're doing
}
do a whole lot of stuff
First; by now, you should use an editor that takes care of indention for you.
Second; Having several return statements can be confusing. One function one exit point.
Third; If "a whole lot of stuff" could be written as separate functions, do it.
But then again, it's all a matter of taste.
Try using switch/case:
function f
{
switch(Z)
{
case X:
do something...
break;
case Y:
do something...
break;
default:
f2();
}
}
function f2{do other stuff...
}