开发者

I keep Getting Control reaches end of non-void function. What am I doing wrong?

location pick(void){    // generates a random location
     location get;
     get.x = rand() % FIELD_SIZE + 1;
     int forY = rand() % FIELD_SIZE +1;
    switch(forY){
    case 1:
        get.y = 'a';
            break;
    case 2:
        get.y = 'b';
            break;
    case 3:
        get.y = 'c';
            break;
    case 4:
        get.y = 开发者_运维百科'd';
            break;
    case 5:
        get.y = 'e';
            break;
    }

}


You're missing return get; at the end of your function.


Make sure to return get; in your function!

Otherwise, you want to declare your function as void pick.


Are you returning a value from your function?


Your function, as written, does not return anything, but it is declared to return a location. You probably want return get; at the end, as Mark said.


You may want to pass the location item by reference to the function. This may reduce the stack size:

void pick(location& get)
{
     get.x = rand() % FIELD_SIZE + 1;
     int forY = rand() % FIELD_SIZE +1;
    switch(forY){
    case 1:
        get.y = 'a';
            break;
    case 2:
        get.y = 'b';
            break;
    case 3:
        get.y = 'c';
            break;
    case 4:
        get.y = 'd';
            break;
    case 5:
        get.y = 'e';
            break;
    }
    return;
}

Also, think about a default case in your switch statement. Error handling now will help prevent wasting later debugging time.

Another suggestion: convert switch statement into a table lookup. This allows the table to change without having to change the code (and retest the function). This can be further extended to placing the data into an external file. The external file allows changes to the data without the need to rebuild the program.


Hmm...now that you've been told how to fix the problem, here's how I'd write the code:

location pick(void){    // generates a random location
     location get;
     get.x = rand() % FIELD_SIZE + 1;
     get.y = rand() % FIELD_SIZE +'a';
     return get;
}

Purely in theory, this isn't entirely portable -- letters aren't required to be contiguous. In reality, the only one known where they aren't contiguous is EBCDIC, and it is contiguous in the range you're using. If you were really concerned about it, however, you could do something like:

location pick(void){    // generates a random location
     static char letters[] = "abcdef";
     location get;
     get.x = rand() % FIELD_SIZE + 1;
     get.y = letters[rand() % FIELD_SIZE];
     return get;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜