Function call as argument to C macro - c++

First a little code:
int counter = 0;
int get_counter() { return counter++; }
#define EVEN_OR_ZERO(cc) ( (cc) % 2 == 0 ? (cc) : 0 )
int next_even_or_zero = EVEN_OR_ZERO(get_counter());
This code might seem OK, but... Let's expand the macro:
int next_even_or_zero = get_counter() % 2 == 0 ? get_counter() : 0;
As you can see the macro will only return odd numbers - which is the opposite of what was expected (or desired).
The question: Is there any way to get this work as intended with a macro? Or is a regular function the only way to go?
//This works as wanted
int even_or_zero(int value) { return value % 2 == 0 ? value : 0; }

#define EVEN_OR_ZERO(cc) even_or_zero(cc)
This may be the perfect answer or a bad joke, depending on why you need a macro, which you haven't told us.

The answer is simple: Don't use a macro, unless there's a good reason for it. This case isn't one of them:
int even_or_zero(int i) {
if (i % 2) {
return 0;
} else {
return i;
}
}

Make two functions.
int getCurrentCounter() { ... } // just return here
int getNextCounter() { ... } // increment here
This is how - in example - sequences is PSQL works.
Also, this seems like very bad code design.
don't use macros in C++, there are more better ways to achieve what you want (usally) without using them
functions with sideeffects on global variables are not that good. Think if it would not be better to create struct/class with it's counter and add methods to it. Or better yet, could hide methods as prive at set methods/class as their friends to limit who can affect counter.

Related

How to avoid duplicate code

As shown in the pictures, the two pieces of code are almost the same with only slight differences. Each duplicate might create some trouble, so if you encounter such situations, how are you supposed to solve them?
Example 1
Example 2
It depends on the case.
In general you would add a function which knows both ways and return the value you need in every case.
So in your case you could do something like
bool myFuction(bool condition, int i, int k)
{
if(condition == true)
{
return (i + MIN_SIZE + k < CK_SIZE);
}
else
{
return (i - MIN_SIZE - k >= CK_SIZE);
}
}
Now you can call myFunction(..)
The bool condition would be the condition wether you decide to use the first or the second way.

How do I fix this runtime error related to div by zero?

Here is the chunk of code in question that I've pulled from my program:
#include <vector>
using namespace std;
vector<double> permittingConstructionCosts(56);
static const int PERMITTING_PERIODS = 0;
static const int CONSTRUCTION_PERIODS = 11;
static const double CONSTRUCTION_COSTS = 2169506;
static const double PERMITTING_COSTS = 142085;
static const int PERMITTING_CONSTRUCTION_PERIODS = PERMITTING_PERIODS + CONSTRUCTION_PERIODS;
void calcExpenses // Calculates permitting and construction expenses
(
vector<double>& expense,
double value1,
double value2
)
{
int i;
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
for (i=PERMITTING_PERIODS + 2; i<expense.size(); i++)
{
if (i < PERMITTING_CONSTRUCTION_PERIODS + 2)
{
expense[i] = value2;
}
}
}
int main()
{
if (PERMITTING_PERIODS != 0)
{
calcExpenses(permittingConstructionCosts, -PERMITTING_COSTS/PERMITTING_PERIODS, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
else
{
calcExpenses(permittingConstructionCosts, 0, -CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
}
return 0;
}
According to ideone (http://ideone.com/LpzUny) the code has a runtime error that returns "time: 0 memory: 3456 signal:11".
I've tried to look for solutions on SO and found the following links:
How can I avoid a warning about division-by-zero in this template code?
How to eliminate "divide by 0" error in template code
However, I don't know how to use templates because I am new to c++ and I'm not sure I need to use them in this case so I have no clue how to adapt those solutions to my particular problem if it's even possible.
I'm pretty sure that the "-PERMITTING_COSTS/PERMITTING_PERIODS" is causing the problem but I thought that simply checking the divisor would solve the problem. This function seems to work for every other value other than 0 but I need to account for the case where PERMITTING_PERIODS = 0 somehow.
I would very much appreciate any help I can get. Thanks in advance!
Edit: I actually do initialize the vector in my program but I forgot to put that in because the size is decided elsewhere in the program. The chunk of code works once I fix that part by putting in a number but my program still has a runtime error when I set PERMITTING_PERIODS to 0 so I guess I have to go bug hunting elsewhere. Thanks for the help!
The problem lies inside the function, which is called by the else statement in the main function:
for (i=0; i<=PERMITTING_PERIODS + 1; i++)
{
expense[i] = value1;
}
Here, PERMITTING_PERIODS is 0, thus you loop from 0 to 2 (inclusive).
However, expense.size() is 0, since your vector is empty. As a result, you are trying to access an empty vector, which causes a segmentation fault.
With that said, print the value of i inside the loop, you should see that you try to access expense[0], but the vector is empty, so it has no first slot (basically it doesn't have any)!!
So replace that with:
expense.push_back(value1);
which will allocate enough space for your values to be pushed into the vector.
The answer given in the cited links, (i.e. "How to eliminate "divide by 0" error in template code") applies equally well here. The other answers were given in the context of templates, but this is completely irrelevant. The sample principle applies equally well with non-template code, too. The key principle is to compute a division, but if the denominator is zero, you want to compute the value of zero instead of the division.
So we want to compute -PERMITTING_COSTS/PERMITTING_PERIODS, but use the value of 0 instead of the division when PERMITTING_PERIODS is 0. Fine:
int main()
{
calcExpenses(permittingConstructionCosts,
(PERMITTING_PERIODS == 0 ? 0: -PERMITTING_COSTS)/
(PERMITTING_PERIODS == 0 ? 1: PERMITTING_PERIODS),
-CONSTRUCTION_COSTS/CONSTRUCTION_PERIODS);
return 0;
}

Type No return, in function returning non-void

My C++ code looks like this:
int f(int i){
if (i > 0) return 1;
if (i == 0) return 0;
if (i < 0) return -1;
}
It's working but I still get:
Warning: No return, in function returning non-void
Even though it is obvious that all cases are covered. Is there any way to handle this in "proper" way?
The compiler doesn't grasp that the if conditions cover all possible conditions. Therefore, it thinks the execution flow can still fall through past all ifs.
Because either of these conditions assume the others to be false, you can write it like this:
int f(int i) {
if (i > 0) return 1;
else if (i == 0) return 0;
else return -1;
}
And because a return statement finally terminates a function, we can shorten it to this:
int f(int i) {
if (i > 0) return 1;
if (i == 0) return 0;
return -1;
}
Note the lack of the two elses.
Is there any way to handle this in "proper" way?
A simple fix is to get rid of the last if. Since the first two are either called or not the third case must be called if you get to it
int f(int i){
if (i > 0) return 1;
if (i == 0) return 0;
return -1;
}
The reason we have to do this is that the compiler cannot guarantee that your if statements will be called in every case. Since it reaches the end of the function and it might not have executed any of the if statements it issues the warning.
Just help the compiler to understand your code. Rewrite the function the following way
int f(int i){
if (i > 0) return 1;
else if (i == 0) return 0;
else return -1;
}
you could also write the function for example like
int f( int i )
{
return i == 0 ? 0 : ( i < 0 ? -1 : 1 );
}
Another way to write the function in one line is the following
int f( int i )
{
return ( i > 0 ) - ( i < 0 );
}
The compiler doesn't know that all options are covered, because in terms of your function's syntax there's nothing to suggest it.
A simplified example:
int f(int i)
if if if
(int > int), return (int == int), return (int < int), return
A clearer structure like if/else with a return in each yields an Abstract-Syntax-Tree which clearly shows there's a return in each case. Yours, however, is dependent on the evaluation of nodes in the AST, which isn't covered in the syntax check (by which you're being issued a warning).
Beyond pure syntax, if the compiler were to rely on "possible" evaluations as well in trying to figure out the behavior of your program, it would ultimately need to entangle itself and probably hitting the halting problem. Even if it managed to cover some cases, this would probably spawn more questions from users than it would answer, and also risk an entirely new level of bugs.

Using local variables vs checking against function return directly

I have a function definition, where i call multiple functions. Even if one of the function fails i need to go ahead and call the rest of the functions and finally return a single error saying whether any of the function call failed. The approach which i had followed was
int function foo()
{
int res, res1, res2, res3;
res1 = function1();
res2 = function2();
res3 = function3();
if (res1 == -1 || res2 == -1 || res3 == -1)
{
res = -1;
}
return res;
}
The possible another approach is
int function foo()
{
int res;
if (function1() == -1)
{
res = -1;
}
if (function2() == -1)
{
res = -1;
}
if (function3() == -1)
{
res = -1;
}
return res;
}
Which is a better approach?
Thanks in advance.
No difference at all, both will be optimized to same machine code. Preference, maintainability, and that depends on team guidelines, preferences.
First priority, make the code correct. That's more important than readability and optimization.
That means you need to consider what the function should return in the case where the functions it calls all succeed.
Many of the answers given to this question change the result returned or might return a failure indication if the 'sub-functions' all succeed. you need to take care not to do this.
Personally, I think the overall form of your first option is pretty good - it makes clear that the 3 sub-functions are called regardless of whether one or more of them fail. The one problem is that it returns an indeterminate result if all those functions succeed.
Be wary of answers that use bitwise-or to combine results - there are at least 2 potential problems:
as John Marshall pointed out in several comments, the order of evaluation is indeterminate. This means that if you simply string the function calls with bitwise-or the functions may be called in any order. This might not be a problem if there are no ordering dependencies between the functions, but usually there are - especially if you don't care about the returned value except as a s success/fail indicator (if you aren't using the return value, then the only reason to call the function is for its side effects)
If the functions can return positive, non-zero values when they succeed, then testing for failure becomes a bit trickier than just checking if the results or'ed together are non-zero.
Given these two potential problems, I think there's little reason to try to do anything much fancier than option 1 (or your second option) - just make sure you set res to a success value (0?) for the situation where none of the sub-functions fail.
What about:
int foo ()
{
bool failed = false;
failed |= (function1() != 0);
failed |= (function2() != 0);
failed |= (function3() != 0);
return failed? -1 : 0;
}
You could also collapse the three calls into a single expression and omit the failed variable altogether (at the expense of readability):
int foo ()
{
return ((function1() != 0) | (function2() !=0 ) | (function3() != 0))? -1 : 0;
}
I like the first approach when function1 function2 and function3 have the same signature because I can put them in a function pointer table and loop over the entries, which makes adding function4 alot easier.
If you can define any precise convention about return values you can simply use bitwise or:
int foo() {
if (function1() | function2() | function3())
return -1;
else
return 0;
}
I like the second approach better. If you want one-liners, you can do something like...
char success = 1;
success &= (foo() == desired_result_1);
success &= (bar() == desired_result_2);
etc.
The 2nd is a "better" approach. However, I'd go more without the needless carrying around of an indicator variable:
if( function2() == -1 ){
return -1;
}
Suggestion: (no magic numbers)
I'd also not use "magic numbers" like you've used it. Instead:
if( check_fail( function2() ) ){
return FAILED;
}
more clearly illustrated what you're thinking. Intent is easier to maintain. Magic numbers can sometimes wind up hurting you. For instance, I've known financial guys who couldn't understand why a transaction costing "$-1.00" caused their application to behave abnormally.
In the first form you're not checking the status until all 3 calls are completed. I think this signals your intent the clearest. The second form more closely resembles the more usual case, where you return early if an error is detected.
It's a subtle thing either way. You shouldn't be asking us strangers on the internet, you should be asking the rest of your team, because they're the ones who will have to live with it.
You use bitwise operators to make a 'neat' variant that doesn't need temp variables and has other fancyness too(with the more advanced operators): return func1()|func2();(this is the same as using logical or, ||). However, if you require checking a specific function in the callee, you can create a bitset: return func1() << 1 | func2(); (this assumes that they return 1 or zero)
I'd vote for the second one as well.
This question reminded me of something similar I do in one of my projects for form validation.
I pass in a reference to an empty string. With each condition I want to check, I either add a line of text to the string, or I don't. If after every test the string is still empty, then there were no errors, and I continue processing the form. Otherwise, I print the string as a message box (which describes the problems), and ask the user to fix the errors.
In this case I don't really care what the errors are, just that there are errors. Oh, and as a bonus, my validation code documents itself a bit because the errors that the user sees are right there.
Use local variable if you need to reuse the result somewhere. Else, call and compare.
int foo() {
return function1() | function2() | function3();
}
Yet another option: pass a pointer to the status variable to each function and have the function set it only if there is an error.
void function1(int *res)
{
bool error_flag = false;
// do work
if (error_flag && (res != NULL)
{
*res = ERROR;
}
}
// similar for function2, function3, ...
int foo()
{
int res = OK;
function1(&res);
function2(&res);
function3(&res);
return res;
}
Since all 3 functions always have to get called first and only then you care about the result, I would go for the first solution, because the order of the statements reflects this. Seems more clear to me. Also, I generally don't like functions that do more than just return a value (i.e. that have side effects) in if-clauses, but that's a personal preference.
This sounds like a job for the abundant Perl idiom "<try something> || die()".
int foo() {
int retVal = 0;
function1() != -1 || retval = -1;
function2() != -1 || retval = -1;
function3() != -1 || retval = -1;
// ...
return retVal;
}
I write it this way:
int foo()
{
int iReturn = 0;
int res1 = function1();
if (res1 == -1)
{
return iReturn;
}
int res2 = function2();
if (res2 == -1)
{
return iReturn;
}
int res3 = function3();
if (res3 == -1)
{
return iReturn;
}
return res;
}
As a coding rule, you should declare your variables as close to the place where it is used.
It is good to use intermediate variable like your res1, res2, res3.
But choose a good name so as you intent is clear when you get the value from the function.
And be careful, in the example you've given us, you never assigned the int res; that may be returned when success. The coding rule is to initialize your variable as soon as you can.
So you should also initialize your res1 res2 res3 immidiatbly.
Returning an uninitialized value leads to undefined behaviour.
I've seen code like this before which might be a little cleaner:
bool result = true;
result = function1() == -1 && result;
result = function2() == -1 && result;
result = function3() == -1 && result;
return result?-1:0;
Edit: forgot about short circuiting.

Why are empty expressions legal in C/C++?

int main()
{
int var = 0;; // Typo which compiles just fine
}
How else could assert(foo == bar); compile down to nothing when NDEBUG is defined?
This is the way C and C++ express NOP.
You want to be able to do things like
while (fnorble(the_smurf) == FAILED)
;
and not
while (fnorble(the_smurf) == FAILED)
do_nothing_just_because_you_have_to_write_something_here();
But! Please do not write the empty statement on the same line, like this:
while (fnorble(the_smurf) == FAILED);
That’s a very good way to confuse the reader, since it is easy to miss the semicolon, and therefore think that the next row is the body of the loop. Remember: Programming is really about communication — not with the compiler, but with other people, who will read your code. (Or with yourself, three years later!)
I'm no language designer, but the answer I'd give is "why not?" From the language design perspective, one wants the rules (i.e. the grammar) to be as simple as possible.
Not to mention that "empty expressions" have uses, i.e.
for (i = 0; i < INSANE_NUMBER; i++);
Will dead-wait (not a good use, but a use nonetheless).
EDIT: As pointed out in a comment to this answer, any compiler worth its salt would probably not busy wait at this loop, and optimize it away. However, if there were something more useful in the for head itself (other than i++), which I've seen done (strangely) with data structure traversal, then I imagine you could still construct a loop with an empty body (by using/abusing the "for" construct).
OK, I’ll add this to the worst case scenario that you may actually use:
for (int yy = 0; yy < nHeight; ++yy) {
for (int xx = 0; xx < nWidth; ++xx) {
for (int vv = yy - 3; vv <= yy + 3; ++vv) {
for (int uu = xx - 3; uu <= xx + 3; ++uu) {
if (test(uu, vv)) {
goto Next;
}
}
}
Next:;
}
}
I honestly don't know if this is the real reason, but I think something that makes more sense is to think about it from the standpoint of a compiler implementer.
Large portions of compilers are built by automated tools that analyze special classes of grammars. It seems very natural that useful grammars would allow for empty statements. It seems like unnecessary work to detect such an "error" when it doesn't change the semantics of your code. The empty statement won't do anything, as the compiler won't generate code for those statements.
It seems to me that this is just a result of "Don't fix something that isn't broken"...
Obviously, it is so that we can say things like
for (;;) {
// stuff
}
Who could live without that?
When using ;, please also be aware about one thing. This is ok:
a ? b() : c();
However this won't compile:
a ? b() : ; ;
There are already many good answers but have not seen the productive-environment sample.
Here is FreeBSD's implementation of strlen:
size_t
strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s)
;
return (s - str);
}
The most common case is probably
int i = 0;
for (/* empty */; i != 10; ++i) {
if (x[i].bad) break;
}
if (i != 10) {
/* panic */
}
while (1) {
; /* do nothing */
}
There are times when you want to sit and do nothing. An event/interrupt driven embedded application or when you don't want a function to exit such as when setting up threads and waiting for the first context switch.
example:
http://lxr.linux.no/linux+v2.6.29/arch/m68k/mac/misc.c#L523