开发者

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?

I am not us开发者_Go百科ed to plain old C... only C++, there might be some kind of subtle difference in how methods are declared.

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.


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.


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. :)


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.

Try adding a printf after doing temp = test(); the compiler will no perform the same optimization again.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜