Can I use the conditional operator in such a way that,if the conditions meets,it will assign the value,and if not it will do nothing.
What I mean is this possible?
apointer=(afunc())?afunc():donothing;
Here, afunc() returns a pointer with the same type as apointer.This function returns NULL value if an error occurs so apointer will be assigned a NULL in this case.How can I avoid that?
Here, afunc() returns a pointer with the same type as apointer.This function returns NULL value if an error occurs so apointer will be assigned a NULL in this case.How can I avoid that?
Use a simple if instead of the conditional operator
But wouldn't it be more efficient to create a pointer on the heap if it was being created in the main function? Assuming that it is being made in the main function.
That way, the pointer would only be on the heap until the assignment was made, then it would be removed from the heap. Rather than creating a pointer on the stack until the program had been exited.
new pointer = afunc();
if( new pointer )
aPointer = new pointer
delete new pointer
ptr is not being stored on the heap, only the object it points to. If it goes out of scope, ptr is destroyed because it's an automatic variable, stack allocated, but the object it points to isn't.
You could also do
apointer = (apointer=afunc()) ? apointer : donothing;
The power of the assignment operator :)
Thanks sachav,that was the power I was looking for :)
although that donothing is still symbolic.
Btw,I think I should use a new dummy pointer to keep the result of the function,in an if statement,as Lynx gave above,to prevent apointer from taking NULL value,because that NULL value creates problem when I display all the pointed objects in the array.
Its nice to read your discussions,but I passed that example using an extra dummy variable. The reason I asked such a question is that,the author of the book is so stingy about memory usage.Otherwise, since Im not coding a program with thousands of hundreds of lines and variables, an extra variable is not problem :)
What Bazzy said. Unless you need to do that with a bazillion recursions you don't really have to care about the memory you need for one extra variable.