Can you use an object's existence as the condition of an if statement in Haxe? If so, how?
var b : Bullet = collide("bullet", x, y);
if (b) {
b.destroy();
}
I've also tried testing it against the Null type, but that doesn't seem to work.
As kirilloid mentions in the comments, try checking if b is not null:
var b : Bullet = collide("bullet", x, y);
if (b != null) {
b.destroy();
}
It was decided for Haxe not to have the if(b) syntax for a number of reasons. You can find a discussion on the topic on Google Groups: Test if exists.
Related
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.
I have an enum with one undefined and two user values:
class enum E
{
UNDEFINED,
VALUE1,
VALUE2
};
I want to add VALUE3 but I'm worried there's a lot of code like:
assert(val != E::UNDEFINED);
if(val == E::VALUE1)
{
}
else
{
// Without an assert this wrongly assumes E::VALUE2
}
and:
something = (val == E::VALUE1) ? a : b; // last part assumes E::VALUE2
I like that compilers warn against switch statements not handling all enumerations and wondered if there is anything similar to show all instances of the above?
I'm concerned I won't find and update all instances of the above.
Compiler is Clang
Enums are not restricted to the values you give names to. From cppreference (formatting is mine):
An enumeration is a distinct type whose value is restricted to a range of values (see below for details),
which may include several explicitly named constants ("enumerators"). The values of the constants are values of an integral type known as the underlying type of the enumeration.
The "below details" explain how the enums underlying type is determined. Out of this range we (usually) give names only to some values as in:
enum foo {A,B,C};
int main() {
foo x = static_cast<foo>(42);
}
This code is completely fine. x has an underlying value of 42. There is no name for the value but this doesn't really matter... unless you assume that it does.
That wrong assumption is made by this code:
assert(val != E::UNDEFINED);
if(val == E::VALUE1)
{
}
else
{
// Without an assert this wrongly assumes E::VALUE2
}
This code is what needs to be fixed (independent of whether you add a new named constant to the enum or not).
Now for a more serious trial to answer the question...
There is no way to get a warning when a chain of if-else does not cover all enum values. What you can do is to turn all if-else uses of the enum into errors. Consider what actually happens here:
if (x == E::VALUE1) do_something();
switch(x) {
case E::VALUE1 : return 1;
}
In the if statement we call operator==(foo,foo); its return value either is a bool or is implicitly converted to one. With the switch none of this is needed. We can make use of this to turn if-else usages of the enum into errors. Bear with me I will explain in two steps. First lets create a compiler error for if( x == E::VALUE1):
class helper {
operator bool(){ return false;}
};
helper operator==(E,E){
return {};
}
Now if (x == E::VALUE1) calls helper operator==(E,E), thats fine. Then the result is converted to bool, and that fails because the conversion is private. Using the enum in a switch is still ok and you can rely on compiler errors / warnings. The basic idea is just to have something that only fails to compile when called (in the wrong/right context). (Live Demo).
The drawback is that also all other used of operator== are broken. We can fix them by modifying the helper and the call sites:
#include <type_traits>
enum E {VALUE1};
struct helper {
bool value;
private:
operator bool(){ return false;}
};
helper operator==(E a,E b){
return {
static_cast<std::underlying_type_t<E>>(a) == static_cast<std::underlying_type_t<E>>(b)
};
}
int main() {
E x{VALUE1};
//if ( x== E::VALUE1); // ERROR
bool is_same = (x == E::VALUE1).value;
switch(x) {
case E::VALUE1 : return 1;
}
}
Yes it is a major inconvenience to have to write .value, but in this way you can turn all uses of the enum in ifs into errors while everything else will still compile. Also note that you have to make sure to cover all cases you want to catch (eg !=,<, etc).
Am reading through (the) C++ Core guidelines and encountered this rule: "Don’t declare a variable until you have a value to initialize it with" https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with
It describes the following code as bad:
SomeLargeType var;
if (cond) // some non-trivial condition
Set(&var);
else if (cond2 || !cond3) {
var = Set2(3.14);
}
else {
var = 0;
for (auto& e : something)
var += e;
}
Unfortunately this point fails to describe a way to how to solve this exact issue. Sometimes you just have to initialize a large object differently depending on a condition.
The only circumvent that comes to my mind is something like:
SomeLargeType * var;
if (cond) // some non-trivial condition
var = new SomeLargeType(123);
else if (cond2 || !cond3) {
var = new SomeLargeType(3.14);
}
However even if I use a smartpointer, this feels somehow unnecessary/unsafe and most of all, worse than the initial way.
What is the optimal solution?
You can use a function. Also, don't use bare pointers with ownership (I assume that there's a guideline for this too). Example:
std::unique_ptr<SomeLargeType>
make_something(bool cond, bool cond23)
{
if (cond)
return std::make_unique<SomeLargeType>(123);
else if (cond23)
return std::make_unique<SomeLargeType>(3.14);
else
return nullptr;
}
// usage
std::unique_ptr<SomeLargeType> var = make_something(cond, cond2 || !cond3);
If there's no way for this function to be reusable, then a lambda might be appropriate, as shown by Sopel
First, there is no undefined behaviour in the original sample code: all possible conditions are taken care of (by the final else block). However, there is potential undefined behaviour in the answers so far given, as they replace the 'good' code in the aforementioned else block with, effectively, no initialisation and the return of a nullptr, which may later be the subject of an attempted dereference.
Also, there is no real need here to complicate matters by replacing the instance variable with a pointer (and this also changes the nature/logic of the code).
Using a lambda (as suggested in the link provided by StaceyGirl) is certainly a good way to go (probably the best, but that may be subjective). However, to keep the logic the same as the original code, one can apply the lambda to the object, rather than to a pointer, as so:
SomeLargeType var = [&]() {
if (cond) { // some non-trivial condition
SomeLargeType v1;
Set(&v1);
return v1;
}
else if (cond2 || !cond3) {
SomeLargeType v2 = Set2(3.14);
return v2;
}
else {
SomeLargeType v3 = 0;
for (auto& e : something) var += e;
return v3;
}
}();
Here, unlike in the original code (where a default constructor is first called, then one of three others), a constructor for SomeLargeObject will only be called once¹ and there will be no undefined behaviour. It is this initial call to the (potentially very expensive) default constructor that, I presume, is the reason for this being cited as an example of "bad code."
¹ If there are any doubts about how often the constructors are called, I can provide a complete MCVE (with some minor modifications to avoid the undefined for (auto& e : something) line), if such is requested.
An immediately invoked lambda can be used as an alternative to a named function.
SomeLargeType* var = [&]() {
if (cond) // some non-trivial condition
return new SomeLargeType(123);
else if (cond2 || !cond3)
return new SomeLargeType(3.14);
else
return nullptr;
}();
Note that some types may not provide a default constructor, in which case it's impossible to have a lazy initialization without using a boxing type.
This can also improve performance when the type is not trivially constructible.
https://godbolt.org/z/_V8t2T
Sometimes, an if statement can be rather complicated or long, so for the sake of readability it is better to extract complicated calls before the if.
e.g. this:
if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
// do stuff
}
into this
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();
if (b1 || b2)
{
//do stuff
}
(provided example is not that bad, it's just for illustration... imagine other calls with multiple arguments, etc.)
But with this extraction I lost the short circuit evaluation (SCE).
Do I really lose SCE every time? Is there some scenario where the compiler is allowed to "optimize it" and still provide SCE?
Are there ways of keeping the improved readability of the second snippet without losing SCE?
One natural solution would look like this:
bool b1 = SomeCondition();
bool b2 = b1 || SomeOtherCondition();
bool b3 = b2 || SomeThirdCondition();
// any other condition
bool bn = bn_1 || SomeFinalCondition();
if (bn)
{
// do stuff
}
This has the benefits of being easy to understand, being applicable to all cases and having short circuit behaviour.
This was my initial solution: A good pattern in method calls and for-loop bodies is the following:
if (!SomeComplicatedFunctionCall())
return; // or continue
if (!SomeOtherComplicatedFunctionCall())
return; // or continue
// do stuff
One gets the same nice performance benefits of shortcircuit evaluation, but the code looks more readable.
I tend to break down conditions onto multiple lines, i.e.:
if( SomeComplicatedFunctionCall()
|| OtherComplicatedFunctionCall()
) {
Even when dealing with multiple operators (&&) you just need to advance indention with each pair of brackets. SCE still kicks in - no need to use variables. Writing code this way made it much more readible to me for years already. More complex example:
if( one()
||( two()> 1337
&&( three()== 'foo'
|| four()
)
)
|| five()!= 3.1415
) {
If you have long chains of conditions and what to keep some of the short-circuiting, then you could use temporary variables to combine multiple conditions. Taking your example it would be possible to do e.g.
bool b = SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
if (b && some_other_expression) { ... }
If you have a C++11 capable compiler you could use lambda expressions to combine expressions into functions, similar to the above:
auto e = []()
{
return SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
};
if (e() && some_other_expression) { ... }
1) Yes, you no longer have SCE. Otherwise, you would have that
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();
works one way or the other depending if there is an if statement later. Way too complex.
2) This is opinion based, but for reasonably complex expressions you can do:
if (SomeComplicatedFunctionCall()
|| OtherComplicatedFunctionCall()) {
If it ways too complex, the obvious solution is to create a function that evaluates the expression and call it.
You can also use:
bool b = someComplicatedStuff();
b = b || otherComplicatedStuff(); // it has to be: b = b || ...; b |= ...; is bitwise OR and SCE is not working then
and SCE will work.
But it's not much more readable than for example:
if (
someComplicatedStuff()
||
otherComplicatedStuff()
)
1) Do I really lose SCE every time? Is compiler is some scenario allowed to "optimize it" and still provide SCE?
I don't think such optimization is allowed; especially OtherComplicatedFunctionCall() might have some side effects.
2) What is the best practice in such situation? Is it only possibility (when I want SCE) to have all I need directly inside if and "just format it to be as readable as possible" ?
I prefer to refactor it into one function or one variable with a descriptive name; which will preserve both short circuit evaluation and readability:
bool getSomeResult() {
return SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall();
}
...
if (getSomeResult())
{
//do stuff
}
And as we implement getSomeResult() based on SomeComplicatedFunctionCall() and OtherComplicatedFunctionCall(), we could decompose them recursively if they're still complicated.
1) Do I really lose SCE every time? Is compiler is some scenario
allowed to "optimize it" and still provide SCE?
No you don't, but it's applied differently:
if (SomeComplicatedFunctionCall() || OtherComplicatedFunctionCall())
{
// do stuff
}
Here, the compiler won't even run OtherComplicatedFunctionCall() if SomeComplicatedFunctionCall() returns true.
bool b1 = SomeComplicatedFunctionCall();
bool b2 = OtherComplicatedFunctionCall();
if (b1 || b2)
{
//do stuff
}
Here, both functions will run because they have to be stored into b1 and b2. Ff b1 == true then b2 won't be evaluated (SCE). But OtherComplicatedFunctionCall() has been run already.
If b2 is used nowhere else the compiler might be smart enough to inline the function call inside the if if the function has no observable side-effects.
2) What is the best practice in such situation? Is it only possibility
(when I want SCE) to have all I need directly inside if and "just
format it to be as readable as possible" ?
That depends.
Do you need OtherComplicatedFunctionCall() to run because of side-effects or the performance hit of the function is minimal then you should use the second approach for readability. Otherwise, stick to SCE through the first approach.
Another possibility that short circuits and has the conditions in one place:
bool (* conditions [])()= {&a, &b, ...}; // list of conditions
bool conditionsHold = true;
for(int i= 0; i < sizeOf(conditions); i ++){
if (!conditions[i]()){;
conditionsHold = false;
break;
}
}
//conditionsHold is true if all conditions were met, otherwise false
You could put the loop into a function and let the function accept a list of conditions and output a boolean value.
Very strange: you are talking about readability when nobody mentions the usage of comment within the code:
if (somecomplicated_function() || // let me explain what this function does
someother_function()) // this function does something else
...
In top of that, I always preceed my functions with some comments, about the function itself, about its input and output, and sometimes I put an example, as you can see here:
/*---------------------------*/
/*! interpolates between values
* #param[in] X_axis : contains X-values
* #param[in] Y_axis : contains Y-values
* #param[in] value : X-value, input to the interpolation process
* #return[out] : the interpolated value
* #example : interpolate([2,0],[3,2],2.4) -> 0.8
*/
int interpolate(std::vector<int>& X_axis, std::vector<int>& Y_axis, int value)
Obviously the formatting to use for your comments may depend on your development environment (Visual studio, JavaDoc under Eclipse, ...)
As far as SCE is concerned, I assume by this you mean the following:
bool b1;
b1 = somecomplicated_function(); // let me explain what this function does
bool b2 = false;
if (!b1) { // SCE : if first function call is already true,
// no need to spend resources executing second function.
b2 = someother_function(); // this function does something else
}
if (b1 || b2) {
...
}
Readability is necessary if you work in a company and your code will be read by someone else. If you write a program for yourself, it is up to you if you want to sacrifice performance for the sake of comprehensible code.
I have to create a C++ program to display the valid LR(0) items in SLR parsing in compiler design. Till now I am able to take the grammar as an input from the user and find its closure. But i am not able to proceed further with the goto implementation in SLR. Can anyone please provide me the links or code as to how to display the valid LR(0) items of a grammar.
-Thanks in advance
You're able to take the closure of the grammar? Technically, the closure function is defined on sets of items (which are sets of productions with a position associated with each production).
Now, you ask for how to display the valid LR(0) items of a grammar. You either mean displaying all the items, as defined in the paragraph above, or displaying all states of the LR(0) automaton. The first is trivial because all possible items are valid, so I'm guessing you want all states. This is what you do (straight from the dragon book).
SetOfItems getValidStates(Grammar G) {
// S' -> S is the "first" production of G (which must be augmented)
SetOfItems C = {[S' -> *S]};
do {
bool added = false;
for (Item I : C) {
for (Symbol X : G) {
L = GOTO(I, X);
if (L.size() > 0 && !C.contains(L)) {
added = true;
C.add(L);
}
}
}
} while (added);
return C;
}
The only question is how to implement GOTO(SetOfItems, Symbol).
So,
SetOfItems GOTO(SetOfItems S, Symbol X) {
SetOfItems ret = {}
for (Item I : S)
if (I.nextSymbol().equals(X))
ret.add(I.moveDotByOne())
return closure(ret);
}
Each item in the set has the form [A -> a*Yb], where A is the head of some production and aXb is the body of the production (a and b are just a string of grammar symbols, Y is a single symbol). The '*' is just the position I mentioned - it's not in the grammar, and [A->a*Yb].nextSymbol() is Y. Basically, Item.nextSymbol() just returns whatever symbol is to the right of the dot. [A->a*Yb].moveDotByOne() returns [A->aY*b].
Now, I just finished the parsing chapter in the compiler book, and I'm not completely happy with my understanding, so be careful with what I've written.
As for a link to real code: http://ftp.gnu.org/gnu/bison/ is where you'll find bison's source, but that's a LALR parser generator, and I don't think it implements LR(0).