我声明并定义一个函数如下:
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;
}
答案 0 :(得分:2)
尝试在main()
中明确声明它如果未正确声明,编译器会假定它默认返回int
答案 1 :(得分: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);
}
请检查这是否适合您,然后将其与您的计划进行比较 确保你已正确宣布该功能。
答案 2 :(得分:1)
您返回的unsigned int
(x)已添加到int
(y),可以是已签名的int
。如果您打算在此函数中仅返回unsigned int
,则不会强制转换第二个操作数(y),这可能会导致未定义的行为。