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
Related
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();
}
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 8 years ago.
Improve this question
I am writing a unit test in C++. My final results in the source code designed to show by
printf("%d\n", ResultA);
and there is no return ResultA.
I have to mention that the ResultA simply comes after a comparison of 3 values so I do not have any function that return me ResultA. Something like this:
if a<b --> ResultA= 1
if a>b --> ResultA= 2
I wonder how in my unit test I can access the ResultA? because I need to have that value and see if it is reported correctly.
You make a function that produces the value and write a unit test for it.
int MakeResultA()
{
return 5;
}
void SomeFunction()
{
int resultA = MakeResultA();
printf("%d\n", resultA);
}
BOOST_AUTO_TEST_CASE(MakeResultA)
{
BOOST_CHECK_EQUAL(MakeResultA, 5);
}
If you are able to refactor your code so that you can access the result as a return value, as suggested by Don, that is definitely the best solution. The answer I am presenting here is somewhat of a nasty hack and it is not for the faint hearted.
It is possible to define your own version of printf, which will capture the value of the argument(s) you want to check.
For example, if the code you want to test looks like this:
//code_to_test.cpp
#include <cstdio>
void myFunction() {
printf("The result is: %d\n", 42);
}
then an example test harness could look like this:
// main.cpp
#include <iostream>
#include <cstdarg>
using namespace std;
void myFunction();
int captured;
int printf(const char *format, ...) {
va_list ap;
va_start(ap, format);
captured = va_arg(ap, int);
va_end(ap);
cout << "Captured :" << captured << endl;
return 1;
}
int main() {
myFunction();
return 0;
}
Compile like this:
g++ -c code_to_test.cpp
g++ main.cpp code_to_test.o
The output you get is this:
$ ./a.out
Captured :42
It works because the linker sees there is a printf function defined in your test harness, and uses that instead of the one in the standard C library.
Needless to say, this approach is fraught with dangers. You need to cater for all combinations of arguments which all calls to printf may make in the code under test, and of course you can't actually use printf anywhere to print anything out.
But if you are in a really tight corner, and considering this is only for a unit test, not production code, I guess it might get you out of trouble.
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 8 years ago.
Improve this question
When I pass some flags to a function, only their values are visible in the function call. The programmer has to look up what the values are corresponding to in the function definition. That often means to look at a different location or start typing the function call again for the IDE hints to show up.
// function definition in header file
void foo(bool output = false, bool formatted = false, bool debug = false);
// function call, it is not intuitive what the values mean
foo(true, false, true);
Is there a coding technique to approach this problem? For example, this pseudo code would be more intuitive, but that obviously isn't valid C++.
// function call with explicit mention of flags that should be true
foo(output, debug);
I know that there are many options for explicitly mentioning the options, often with an overhead of needed computation or syntax, like using a std::unordered_map of options. The syntax overhead becomes less with C++11 initializer lists. However, I would like to stick to a common practice if that exists.
In C++11, you could use scoped enumerations:
foo(output::yes, formatted::no, debug::yes);
(If you're stuck in the past, you can do something similar, but less elegant, with regular enumerations).
There's also the old-school method of combining single-bit flag values:
enum {
output = 1 << 0,
formatted = 1 << 1,
debug = 1 << 2
};
foo(output | debug);
The way I prefer is simply not to overload on bools in the user interface:
foo( /* non-bool parms ... */);
foo_formatted( /* non-bool parms ... */);
foo_debug( /* non-bool parms ... */);
with perhaps a hidden implementation with overloading as in OP's question.
You could use Named Parameter Idiom.
struct call_foo {
call_foo& formatted() { formatted_ = true; }
call_foo& debug() { debug_ = true; }
call_foo& output() { output_ = true; }
~call_foo() { foo(output_, formatted_, debug_); }
private:
bool formatted_ = false;
bool debug_ = false;
bool output = false;
};
Usage:
call_foo().debug().formatted();
You can extend it so that methods of call_foo take parameters, too.
I have seen three different ways to handle such situations in differnet coding styles:
Add comments explaining the semantics:
foo(true /* with output */, false /* not formatted */, debug /* debug on* /);
Use a macro which always expands to true and which takes an argument giving the semantics, e.g.
#define K(Name) true
foo(K(Output), !K(Formatted), K(Debug));
Use enums (this requires changing the signature of the function):
enum OutputMode { WithOutput, WithoutOutput };
enum FormattingMode { WithFormatting, WithoutFormatting };
enum DebugMode { WithDebug, WithoutDebug };
foo(WithOutput, WithoutFormatting, WithDebug);
If I have to use interfaces like foo, I usually end up with the first version. When designing APIs, I try to avoid having functions taking more than one bool - and if I do want it, I like the third version because it's type safe.
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!
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).