3

我声明并定义一个函数如下:

unsigned int doSomething(unsigned int *x, int y)
{
    if(1) //works
    if(y) //reports the error given below

    //I use any one of the ifs above, and not both at a time

    return ((*x) + y); //works fine when if(1) is used, not otherwise
}

我从 main() 调用函数如下:

unsigned int x = 10;
doSomething(&x, 1);

编译器报错和警告如下:

passing argument 1 of 'doSomething' makes pointer from integer without a cast [enabled by default]|

note: expected 'unsigned int *' but argument is of type 'int'|

我尝试对函数返回类型、函数调用以及参数类型使用所有可能的组合。我哪里错了?

完整代码:

unsigned int addTwo(unsigned int *x, int y)
{
    if(y)
        return ((*x) + y);
}
int main()
{
    unsigned int operand = 10;
    printf("%u", addTwo(&operand, 1));
    return 0;
}
4

3 回答 3

2

尝试在 main() 中显式声明它

如果没有正确声明,编译器假定它默认返回 int

于 2013-02-25T10:12:26.023 回答
1

我也在 Windows 上使用过 gcc 4.4.3。
该程序编译成功并产生输出“11”:

#include <stdio.h>

unsigned int doSomething(unsigned int *x, int y);

int main()
{
    unsigned int res = 0;
    unsigned int x = 10;

    res = doSomething(&x, 1);

    printf("Result: %d\n", res);

    return 0;
}

unsigned int doSomething(unsigned int *x, int y)
{
    if(y)
    {
        printf("y is ok\n");
    }

    if(1)
    {
        printf("1 is ok\n");
    }

    return ((*x) + y); 
}

请检查这是否适合您,然后将其与您的程序进行比较。
确保您已正确声明该函数。

于 2013-02-25T10:14:21.527 回答
1

您将返回一个unsigned int(x) 添加到一个int(y) 中,该 (y) 可以是一个已签名的int。如果不强制转换第二个操作数 (y),如果您打算仅unsigned int在此函数中返回,这可能会导致未定义的行为。

于 2013-02-25T10:16:38.803 回答