ecmadeeasy
ecmadeeasy

Reputation: 17

Solution for compiler warning: control reaches end of non-void function

I have the following code:

int cons_col()
{
for(int col =0; rx_state_== MAC_IDLE; col++)
return col;
}

It is like a counter that is supposed to return an integer when the condition rx_state_ == MAC_IDLE is met; When I compile, I get the warning: control reaches end of non-void function.

Will this problem go away if add the following at the end of above function:

if (coll == 0)
return 0;

Upvotes: 2

Views: 292

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63838

That code evaluates to this.

int cons_col()
{
    for( int col = 0; rx_state_ == MAC_IDLE; col++ )
    {
       return col;
       // "return" prevents "col++" (above) from EVER being evaluated. 
    }
    // What happens here?  What int gets returned?
}

Note that this function will always immediately complete.

It does this:

  • Sets an integer col to 0.
  • Checks once if rx_state_ is MAC_IDLE.
  • If it is, it returns 0
  • If it isn't, it gets to // What happens here?, and then reaches the end of the non-void function without returning anything, invoking Undefined Behavior.

From your description, you probably wanted something like this.

int cons_col()
{
    int col = 0;
    for( ; rx_state_ != MAC_IDLE; col++ )
    {
       // You may want some type of sleep() function here.
       // Counting as fast as possible will keep a CPU very busy
    }
    return col;
}

Upvotes: 6

Related Questions