C/C++ function as parameter - c++

bool isContainedSameForm(AG ag1, AG ag2){
if(isEmpty(ag2)) return false;
return isContainedSameForm(ag1->pH,ag2->pH) && isContainedSameForm(ag1->sH,ag2->sH);
};
int sameFormOcurrences(AG ag1,AG ag2,bool (*isContainedSameForm)(AG,AG)){
if(isEmpty(ag2)) return 0;
int ret=0;
if(isContainedSameForm(ag1,ag2)) ret=1;
return ret + sameFormOcurrences(ag1,ag2->pH,isContainedSameForm) + sameFormOcurrences(ag1,ag2->sH,isContainedSameForm);
};
int sameFormOcurrences( AG ag1, AG ag2){
return sameFormOcurrences(ag1,ag2,isContainedSameForm);
}
AG being a general tree, this counts how many times a tree of the same form appears in the second tree
What I don't understand is the purpose of the first sameFormOcurrences function receiving a isContainedSameForm in parameters.
Is is just a way to change the signature without changing the name of it?
Isn't it redundant with the function being declared above already if it's trying to avoid a non defined method?

This code isn't written in the best style, the function pointer parameter, and the function implementing that, really should have different names. Right now if there were a typo in the parameter declaration, the code inside the function would refer directly to another function, and the parameter would silently become useless.
This would be much better:
int countMatchingDescendants(AG ag1,AG ag2,bool (*matchCondition)(AG,AG))
{
if(isEmpty(ag2)) return 0;
int ret=0;
if(matchCondition(ag1,ag2)) ret=1;
return ret + countMatchingDescendants(ag1,ag2->pH,matchCondition) + countMatchingDescendants(ag1,ag2->sH,matchCondition);
}
bool isContainedSameForm(AG ag1, AG ag2)
{
if(isEmpty(ag2)) return false;
return isContainedSameForm(ag1->pH,ag2->pH) && isContainedSameForm(ag1->sH,ag2->sH);
}
int sameFormOcurrences( AG ag1, AG ag2)
{
return countMatchingDescendants(ag1,ag2,isContainedSameForm);
}
Note that I've only changed identifier names, not the structure of the code (I also removed extraneous semicolons outside the function bodies). But now the counting code has a generic name indicating how flexible it actually is.
By changing the order, I prevent any possibility of the generic counting code accidentally referring to a concrete implementation.

Related

Objects vs. Static Variables for retaining function state

I have a function which processes data that comes as a sequence. Because of this, I need to know the value of certain variables from the last function call during the current function call.
My current approach to doing this is to use static variables. My function goes something like this:
bool processData(Object message){
static int lastVar1 = -1;
int curVar1 = message.var1;
if (curVar1 > lastVar1){
// Do something
}
lastVar1 = curVar1;
}
This is just a small sample of the code; in reality I have 10+ static variables tracking different things. My gut tells me using so many static variables probably isn't a good idea, though I have nothing to back that feeling up.
My question: Is there a better way to do this?
An alternative I've been looking into is using an object whose fields are lastVar1, lastVar2, etc. However, I'm not sure if keeping an object in memory would be more efficient than using static variables.
Your question has a taste of being purely about style and opinions, though there are aspects that are not a matter of opinion: multithreading and testing.
Consider this:
bool foo(int x) {
static last_val = -1;
bool result = (x == last_val);
last_val = x;
return result;
}
You can call this function concurrently from multiple threads but it wont do the expected. Moreover you can only test the function by asserting that it does the right thing:
foo(1);
assert( foo(1) ); // silenty assumes that the last call did the right thing
To setup the preconditions for the test (first line) you already have to assume that foo(1) does the right thing, which somehow defeats the purpose of testing that call in the second line.
If the methods need the current object and the previous object, simply pass both:
bool processData(const Object& message,const Object& previous_message){
if (message.var1 > previous_message.var1){
// Do something
return true;
}
return false;
}
Of course this just shifts the issue of keeping track of the previous message to the caller, though thats straight-forward and requires not messing around with statics:
Object message, old_message;
while ( get_more( message )) {
processData(message, old_message);
old_message = message;
}

How can i use bool to create a file

Hi can someone help me with this function:
bool createfile (string path);
It is supposed to create a file but my problem is:
What exactly the true or false have to do with creating a file?! How can I use it?
The bool is the return type of the function createfile(). Without the definition it is impossible to tell for sure what exactly this value is supposed to be, but often it is used to return if the function was successful in doing what it is supposed to do, in this case, create a file.
What exactly the true or false have to do with creating a file?!
You might want to return true if the file was successfully created or false otherwise.
How can I use it?
This depends on the body of the function and the purpose that you want to use the function for.
Quick answer
To directly answer the "How can I use it" part of your question:
You call it this way:
string path = "/path/to/my/file.txt";
bool returnedValue = createfile(path);
As for "What exactly the true or false have to do with creating a file?!", like mentionned in the other answers, it might indicate the success or failure of the operation, but you might want to double-check that, because the actual value will depend on the implementation of bool createfile(string path)...
Comprehensive answer
It seems you need some help interpreting the syntax of bool createfile(string path);
What we need to clarify here is that in c++ (and many other languages), the first word used in the function declaration is the return type.
You could compare this to some arbitrary mathematical function of the following form: here
x = a + b
In this case, x is the result of the addition function.
Assuming all the elements above are numbers, we could translate this in c++, like so:
int a = 0;
int b = 5;
int x = a + b;
We could extract the example above in a function (to reuse the addition), like so:
int add(int a, int b)
{
return a + b;
}
and use it in the following way (with a main to put some execution context around it):
int main()
{
int x = add(0,5);
return 0;
}
Here are some other examples of functions:
// simple non-member function returning int
int f1()
{
return 42;
}
// function that returns a boolean
bool f2(std::string str)
{
return std::stoi(str) > 0;
}
You'll find more details here. It might seem like a lot to take in (the page is dense with information), but it is a true reference.

How to neatly write two functions - one for checking if a solution exists, and another one for getting all solutions?

The obvious way is to just write two functions, but then they are almost identical. What I'm doing now is a function template with the return type (either bool or vector<something>) as the argument
template<typename ReturnType>
ReturnType foo(...){
constexpr bool return_bool = std::is_same<ReturnType, bool>::value;
ResultType results; //hopefully, the compiler takes it out in the bool case
And the plan is to use if constexpr(return_bool) when needed. But then I get this reoccurring piece of code
ReturnType result = foo<ResultType>(...);
if constexpr(return_bool){
if(result) return true;
}else std::copy(result.begin(), result.end(), std::back_inserter(results));
The return statement makes it hard to use standard anti-repetition techniques. I could use macros but then perhaps the repetition is better. Getting either all solutions or just the information whether one exists seems like a fairly general problem, is there a better way to do it?
I should've added that the function is performance-critical in the "does a solution exist?" case. That's why I want to have another version there and also why I don't want any costly abstractions.
You want two opposite features :
Reusing one solution in the other to avoid replication
Having an optimized version for solutionExists() to avoid a full result search
You didn't specify what is the solution your function returns, so I will explain why you can't have both using a simple example : your function is returning the number of ocurences of 0 in a vector of integers.
The function returning all solutions would look like this :
int GetNumberOfOccurencesOf0(const vector<int>& data)
{
int occurences = 0;
for (int i : data)
{
if (i == 0)
++occurences;
}
return occurences;
}
If you are not concerned about performance, your function for returning if there is a solution can be :
bool AreThereOccurencesOf0(const vector<int>& data)
{
return (GetNumberOfOccurencesOf0(data) > 0);
}
Note that there is no code duplication but the solution is not optimal : the data vector is iterated entirely. If you want an optimized solution, it would look like this :
bool AreThereOccurencesOf0(const vector<int>& data)
{
for (int i : data)
{
if (i == 0)
return true;
}
return false;
}
If your problem requires an optimized version of solutionExists(), you should write it and it should not need to reuse code from the getAllSolutions() function.

How to elegantly implement single methods with variable output?

I am trying to improve my code style.
Sometimes I have methods that do complicated checks or computations and depending on the context of the calling method I need different results from these algorithms. Let's assume that there is one result, that is always needed and it will be the return value of the method. But how to deal with the optional other results? Of course I want to implement my complicated method only once. Therefore I have introduced modifiable reference parameters and depending on some conditions they are overwritten with these additional results.
As a convenience for those contexts where I don't need the additional results, I have introduced overloads that create dummy variables that are passed to the single implementation.
Please see the following simplified example code:
#include <iostream>
/**
* \brief Checks whether everything is okay.
*
* \param isCheckedFirstTime if point is not null, it will be overwritten with
* whether this method has been called for the first time
*
* \returns okay or not
*/
bool isOkay(bool*& isCheckedFirstTime)
{
static bool isFirstTime = true;
if (nullptr != isCheckedFirstTime)
{
*isCheckedFirstTime = isFirstTime;
}
isFirstTime = false;
return true;
}
/**
* \brief Checks whether everything is okay.
*
* \returns okay or not
*/
bool isOkay()
{
bool* dummy = nullptr;
return isOkay(dummy);
}
int main()
{
const bool okay = isOkay();
std::cout << "Is everything okay?: " << okay << std::endl;
return 0;
}
Obviously I could get rid of a lot of boilerplate code by adding a default value for the parameter isCheckedFirstTime like this
bool isOkay(bool*& isCheckedFirstTime = nullptr)
which is not legal, because I cannot bind a non-const lvalue reference to an rvalue of the corresponding type.
Is there a workaround for that? Or is there another possibility to have only one method doing all the computations without overloads for different outputs and without having to declare dummy paramters in the calling code?
One solution I could think of is packing all possible results into one std::tuple. Then the caller can use what he wants. But it might have a disadvantage, if calculation of optional results is costly. Then having a condition (like nullptr != ...) saves computation time if nobody needs the result.
I am looking forward to your proposals!
Usually this is done by returning std::tuple.
In your case it will look something like:
std::tuple<bool,bool> isOkay()
{
static bool isFirstTime = true;
bool isCheckedFirstTime = isFirstTime;
isFirstTime = false;
return std::make_tuple(true, isCheckedFirstTime);
}
In case when you need to return optional complex object or you don't want to calculate unneeded value, it's better to use std::optional if you can use C++17.
std::tuple<bool,std::optional<bool>> isOkay(bool needCheckFirstTime = false)
{
static bool isFirstTime = true;
std::optional<bool> isCheckedFirstTime;
if (needCheckFirstTime) {
isCheckedFirstTime = isFirstTime;
}
isFirstTime = false;
return std::make_tuple(true, isCheckedFirstTime);
}
Therefore I have introduced modifiable reference parameters and depending on some conditions they are overwritten with these additional results.
Out parameters should be avoided like plague. If a function produces a result, it should be a part of its return type. So how we figure out such type for your case?
You've suggested a tuple; in this case, a struct or a tuple would work well.
But it might have a disadvantage, if calculation of optional results is costly.
Sure, but there's nothing that says you have to necessarily tie the arguments to the results. A function could take a bitset or similar enumeration telling it exactly what to compute, and return a struct full of optional values. The specific will largely depend on the specific case being solved.
It appears that you're in doubt whether isCheckedFirstTime should be a pointer or a reference, so you made it both. That's just inconvenient.
This might be more expressive:
bool isOkay(std::optional<bool>& isCheckedFirstTime)
{
static bool isFirstTime = true;
if (isCheckedFirstTime)
{
*isCheckedFirstTime = isFirstTime;
}
isFirstTime = false;
return true;
}
bool isOkay()
{
std::optional<bool> dummy;
return isOkay(dummy);
}

Defining const "variable" inside if block

I have the following code:
Foo a;
if (some_fairly_long_condition) {
a = complicated_expression_to_make_foo_1();
} else {
a = complicated_expression_to_make_foo_2();
}
I have two issues with this:
a is a const and should be declared so
the "empty" constructor, Foo() is called for no reason (maybe this is optimised away?)
One way to fix it is by using the ternary operator:
const Foo a = some_fairly_long_condition?
complicated_expression_to_make_foo_1():
complicated_expression_to_make_foo_2();
Is this good practice? How do you go about it?
To answer the second part of your question:
I usually put the initialization code into a lambda:
const Foo a = [&]()->Foo{
if (some_fairly_long_condition) {
return complicated_expression_to_make_foo_1();
} else {
return complicated_expression_to_make_foo_2();
}
}();
In most cases you should even be able to omit the trailing return type, so you can write
const Foo a = [&](){ ...
As far as the first part is concerned:
I'd say that greatly depends on how complex your initialization code is. If all three parts are really complicated expressions (and not just a function call each) then the solution with the ternary operator becomes an unreadable mess, while the lambda method (or a separate named function for that matter) allows you to break up those parts into the respective sub expressions.
If the problem is to avoid ternaty operator and your goal is to define the constant a, this code is an option:
Foo aux;
if (some_fairly_long_condition) {
aux = complicated_expression_to_make_foo_1();
} else {
aux = complicated_expression_to_make_foo_2();
}
const Foo a(aux);
It is a good solution, without any new feature ---as lambdas--- and including the code inline, as you want.