简体   繁体   English

C-函数未返回值?

[英]C - Function not returning value?

I have the following method defined in my header file 我在头文件中定义了以下方法

unsigned char test(void);

Implementation: 实现方式:

unsigned char test()
{
  unsigned char value = 0xFF;
  return value;    
}

When I call it with this: 当我这样称呼它时:

 unsigned char temp;
 temp = test();

Nothing is returned??? 什么都没有退还? I stepped through it with breakpoints. 我通过断点来完成它。 At the very end, the variable value has a value of 0xFF, but it is never returned to temp? 最后,变量值的值为0xFF,但永远不会返回到temp?

I am not used to plain old C... only C++, there might be some kind of subtle difference in how methods are declared. 我不习惯普通的旧C ...只有C ++,方法的声明方式可能会有一些细微的差别。

Any help would be greatly appreciated!!! 任何帮助将不胜感激!!!

I think you just see a clever compiler. 我认为您只是看到了一个聪明的编译器。 If your variable is never used after the assignment it is just optimized out. 如果分配后从未使用过变量,则会对其进行优化。 The function is still called for its possible side effect, though. 尽管如此,该函数仍因其可能的副作用而被调用。

If you change your variable to a global, the compiler can't know that you will not use it, so it does the assignment, then. 如果将变量更改为全局变量,则编译器将无法使用该变量,因此它会执行赋值操作。

I think if you'd put a printf after the assignment or declare your tmp variable volatile you'd observe the assignment in the debugger as well. 我认为,如果您将printf放在赋值之后,或者将tmp变量声明为volatile那么您也会在调试器中观察到赋值。

Sure its not user error of debugger? 确定不是调试器的用户错误? Most debuggers wont show the value of the variable "temp" until the next line of code, when the assignment has actually been performed. 在实际执行赋值操作之前,大多数调试器都不会显示变量“ temp”的值,直到下一行代码为止。

If optimizations are enabled, temp may be kept in a register, and sometimes debuggers will have trouble finding and displaying these values. 如果启用了优化,则温度可能会保存在寄存器中,有时调试器将难以查找和显示这些值。 Actually, the compiler could very well discard the return value if you don't use it anywhere. 实际上,如果您不在任何地方使用返回值,编译器都可以很好地丢弃它。 Make sure your code is compiled without any optimizations for debug purposes. 确保出于调试目的而对代码进行编译,而没有进行任何优化。

Alternatively, use the oldest method known to men for debugging: printf . 或者,使用人类已知的最旧的方法进行调试: printf :) :)

It the function call has been optimized away by your compiler, the compiler noticed that you are doing nothing with temp and your function call has no side effects, so it optimized it out. 如果您的编译器已对函数调用进行了优化,编译器会注意到您使用temp并没有执行任何操作,并且函数调用没有副作用,因此对其进行了优化。

Try adding a printf after doing temp = test(); 尝试在执行temp = test();之后添加一个printf temp = test(); the compiler will no perform the same optimization again. 编译器将不会再次执行相同的优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM