函数不返回预期值

时间:2017-08-18 18:09:08

标签: c++ function return-value

我没有从函数“checkPos”返回正确的值到变量“thesi1。在Windows中使用CodeBlocks。任何建议。

int checkPos(int thesi)
{
    switch(thesi)
    {
        case 6:
            thesi = 4;
            break;
        case 3:
            thesi = 8;
            break;
        case 7:
            thesi = 3;
            break;
        case 9:
            thesi = 16;
            break;
        case 14:
            thesi = 10;
            break;

        return thesi;
    }
}


 int main(){ 

    thesi1 = checkPos(newPos);
    cout << "your position is " << thesi1 << endl;

2 个答案:

答案 0 :(得分:1)

您需要移动return语句,使其恰好在}语句的结束switch之后。如上所述,由于return语句后没有switch语句,因此您的函数具有未定义的行为。您应该调高编译器的警告级别以检测此类错误。

int checkPos(int thesi)
{
    switch(thesi)
    {
        case 6:
            thesi = 4;
            break;
        case 3:
            thesi = 8;
            break;
        case 7:
            thesi = 3;
            break;
        case 9:
            thesi = 16;
            break;
        case 14:
            thesi = 10;
            break;
    }
    return thesi;
}

答案 1 :(得分:0)

如果不在列表值

中,您错过的内容和默认情况一样
#include<iostream>
using namespace std;

int checkPos(int thesi)
{
    switch (thesi)
    {
    case 6:
        thesi = 4;
        break;
    case 3:
        thesi = 8;
        break;
    case 7:
        thesi = 3;
        break;
    case 9:
        thesi = 16;
        break;
    case 14:
        thesi = 10;
        break;
    default:
        cout << thesi<<" Not in the list"<<endl;
        return -1;

    }
    return thesi;
}


int main() {
    int newPos;
    int thesi1 = checkPos(0);
    cout << "your position is " << thesi1 << endl;
}

输出

0 Not in the list
your position is -1
相关问题