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.
Related
I am working on a problem that requires me to return different return-types based on my function parameter values that I provide.
I want to do something like this --
In the code below, doSomething() is an already existing function (used by a lot of clients) which takes mode as a function parameter, and returns std::list<ReturnType> already.
Based on the mode value, I had to create another sub-functionality which returns a shared_future<std::list<ReturnType>>.
How can I change this code so that it can return one of the two return types based on the mode value?
Note: ReturnType is a template typename which we are using for the entire class.
Code:
std::shared_future<std::list<ReturnType> > futureValue() {
return functionReturningSharedFuture();
}
std::list<ReturnType> listValue() {
return functionReturningList();
}
std::list<ReturnType> doSomething(int mode) {
if(mode == 1){
// new functionality that I added
return futureValue(); // This (obviously) errors out as of now
}
else{
// already there previously
return listValue();
}
}
int main() {
doSomething(1);
return 0;
}
How can I change this code so that it can return one of the two return types based on the mode value?
Constraints and Issues:
This issue could've been easily solved by function overloading if we provide an extra function parameter (like a true value), but that extra argument is not useful, since we are already using mode. Also, it isn't considered a good design to add variables which have almost no use.
One of the major constraints is that there are clients who are already using this doSomething() expect a std::list<ReturnType>, and so I cannot return boost::any or std::variant or anything similar.
I tried using std::enable_if, but it wasn't working out since we are getting the mode value at runtime.
We can't use template metaprogramming since that would change the way our function is being called on the client-side. Something that we can't afford to do.
Thank you.
This cannot be done.
You can only have one function with a given signature. If you have calling code that already expects this to return a std::list<ReturnType>, that's it; you're done.
If you could guarantee that all existing calling code looks like
auto l = obj.doSomething(1);
then you could potentially change the return type to something which would look like a std::list to any calling code. But if there's any calling code that looks like
std::list<ReturnType> l = obj.doSomething(1);
then that's off the table.
You probably need to rethink your design here.
From the example main, I see doSomething(1);, so maybe at the call site the value of the parameter mode is always known at compile-time. In this case, one option is that you make doSomething a template<int mode> function. I'm thinking about something like this:
#include <iostream>
#include <list>
#include <vector>
// assuming you cannot change this (actually you have changed it in you example, ...)
std::list<int> doSomething(int mode) {
std::cout << "already existing function\n";
return std::list<int>{1,2,3};
}
// then you can put this too
template<int N>
auto doSomething();
template<>
auto doSomething<10>() {
std::cout << "new function\n";
return std::vector<int>{1,2,3};
}
int main() {
auto x = doSomething(3);
auto y = doSomething<10>();
}
Probably another option would be to use a if constexpr intead of if and an auto/decltype(auto) return type in doSomething, but I haven't tried it.
Why in C++ do we use SetCursorPos(10,20); instead of BOOL SetCursorPos(10,20);? Why is the second one throwing compilation errors? The MSDN specification says to use BOOL and it's not good why?
Looking at the MSDN docs you can see it shows the function declaration as:
BOOL SetCursorPos(int X, int Y);
That means the functions takes two integer parameters and returns a boolean result.
The return value indicates if the call was successful or not.
If you try to type:
BOOL SetCursorPos(10, 20);
That doesn’t really make sense as the initial 'BOOL' should be used for declaring a variable to store the result. You could do something like:
BOOL result = SetCursorPos(10, 20);
if (result == 0) {
std::cout << “failed to set cursor position”;
}
Or if you don’t care about the return value you can just do nothing with it like this:
SetCursorPos(10, 20);
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.
I am wondering if there is a better way to write this for better readability.
If you have a function like below,
void animal(bool hasFourLegs, bool hasHead, bool hasBody);
When you call the function, you will end up with something like
animal(true, false, true);
and this makes me go take a look at the definition every time I encounter function like this.
SO...
I do something like this!
const bool HAS_FOURLEGS = true;
const bool NO_HEAD = false;
const bool HAS_BODY = true;
animal(HAS_FOURLEGS, NO_HEAD, HAS_BODY);
But I do not like to declare const bool every time I call the function.
It seems like CPP does not support something like
animal(bool hasFourlegs = true, bool hasHead = false, bool hasBody = true);
Is there any better and shorter way?
When I run into issues related to this I sometimes create an enum even when there are only 2 expected choices:
For example, instead of the following function declaration:
bool search(..., bool recursive);
I'd go with:
enum class SearchOpt
{
Recursive,
NonRecursive
};
bool search(..., SearchOpt opt);
Therefore, the calling syntax changes from:
bool found = search(..., true);
to:
bool found = search(..., SearchOpt::Recursive);
Note: this avoids you having to create your own constants every time you call the function.
Edit
As others have suggested, instead of having separate bools for each option and thereby a separate enum for each it would make sense to have a single enum configured as bit flags.
Use flags:
enum {
HAS_LEGS = 0x01,
HAS_HEAD = 0x02,
HAS_BODY = 0x04,
};
void animal(int properties);
animal(HAS_LEGS | HAS_HEAD);
One other option is to use a class to hold the parameters where they're closely related:
struct AnimalOptions {
bool hasHead, hasBody, hasLegs;
AnimalOptions() : hasHead(false), hasBody(false), hasLegs(false);
}
...
AnimalOptions opt;
opt.hasHead = true;
animal(opt);
This technique is useful whenever you have a function which seems to take a bunch of parameters with identical types, whose order isn't easily remembered. It's just as useful when your function take several ints.
As a alternative to the other answers, I liked tagged_bool that Andrzej Krzemieński came up with on his blog.
Strange no one suggested named parameters from Boost.parameter: http://www.boost.org/doc/libs/1_59_0/libs/parameter/doc/html/index.html
Comments are your friends!
animal( true, //hasFourLegs
false, //hasHead
true //hasBody
);
You could use bitwise values, as follows:
const int hasLegs = 0x01;
const int noHead = 0x02;
const int hasBody = 0x04;
Then call animal with any combination of the above, e.g.:
animal(hasLegs + hasBody);
Decalre animal with a single int parameter.
inside `animal`, test the bits:
if (parameter & haasBody)
{
// it has a body....
}
C++20 has designated initializers as part of aggregate initialization. You could make a struct with the boolean parameters and pass the struct by value. You can even have default parameter values.
struct AnimalParts {
bool hasFourLegs = false;
bool hasHead = true;
bool hasBody = true;
}
void animal(AnimalParts parts);
Then use it like this:
animal({.hasFourLegs = true, .hasHead = false});
This comes very close to the named parameters idiom you suggested. In terms of compilation both options seem to produce comparable output, see on Godbolt.
I'm not sure it's a correct way to go, but still I cannot resist sharing this thought.
Let's imagine the function is not yours, but rather from some popular API which is hard to change.
void animal(bool hasFourLegs, bool hasHead, bool hasBody);
In this case it's possible to call it like this:
animal(bool("hasFourlegs"), !bool("hasHead"), bool("hasBody"));
The C-string is always a non zero pointer, which is converted to true.
One possible downside is compilation time...?
Another is increase in length of code rows...
What does the following code do in C/C++?
if (blah(), 5) {
//do something
}
Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.
If the comma operator is not overloaded, the code is similar to this:
blah();
if (5) {
// do something
}
If the comma operator is overloaded, the result will be based on that function.
#include <iostream>
#include <string>
using namespace std;
string blah()
{
return "blah";
}
bool operator,(const string& key, const int& val) {
return false;
}
int main (int argc, char * const argv[]) {
if (blah(), 5) {
cout << "if block";
} else {
cout << "else block";
}
return 0;
}
(edited to show comma operator overloading scenario. thanks to David Pierre for commenting on this)
I know one thing that this kind of code should do: it should get the coder fired. I would be quite a bit afraid to work next to someone who writes like this.
In the pathological case, it depends on what the comma operator does...
class PlaceHolder
{
};
PlaceHolder Blah() { return PlaceHolder(); }
bool operator,(PlaceHolder, int) { return false; }
if (Blah(), 5)
{
cout << "This will never run.";
}
I would say that depends on blah().
On a more broad answer. The comma operator (non overloaded) resolves as in, execute the first part and return the second part.
So if you have (foo(),bar()) Both functions will be executed, but the value of the expression evaluates to bar() (and the type of the expression as well).
While I won't say there are fair usages for that, is usually considered a bit hard to read code. Mainly because not many languages shares such constructs. So As a personal rule of thumb I avoid it unless I am adding code to a preexistent expression and don't want to change completely its format.
Example: I have a Macro (not discussing if you should use macros or not, sometimes its not even you that wrote it)
FIND_SOMETHING(X) (x>2) ? find_fruits(x) : find_houses(x)
And I usually use it in assignments like my_possession = FIND_SOMETHING(34);
Now I want to add log to it for debuggin purposes but I cannot change the find functions,. I could do :
FIND_SOMETHING(X) (x>2)? (LOG("looking for fruits"),find_fruits(x)):(LOG("looking for houses"),find_houses(x))
I use sometimes constructs like this for debugging purposes. When I force the if close to be true regardless of the return value of blah.
It's obvious that it should never appear in production code.
The following was written assuming it is C code, either in a C file or within a C block of a C++ file:
It is a pointless if. It will call blah(), however the result of blah() is not considered by if at all. The only thing being considered is 5, thus the if will always evaluate to true. IOW you could write this code as
blah();
// do something
without any if at all.