Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

memory - How do C++ progs get their return value, when a return is not specified in the function?

I recently wrote a post:
Weird Error in C++ Program: Removing Printout Breaks Program

...in which I was trying to solve a seemingly baffling problem, in which removing a cout statement would break my program.

As it turned out, my problem was that I forgot to return my true/false success flag that I was later using for logic.

But apparently SOMETHING was being returned and that something was always true if I left that cout in, but would seemingly "magically" become false when I took it out.

My question for you all is:
What determines what a c++ function return when no return command is executed within the function? Is there any logic to it?

Obviously forgetting your return type is a bad idea. In this case, though, it was largely due to the nature of my program -- a quick hack job. I later decided that it wasn't worth the effort to include implement an algorithm to determine the success/failure of the function call -- but accidentally left behind the code dependent on the return.

Bafflingly g++ gave me no warnings or errors when compiling the executable like so:

g++ main.cc -g -o it_util

My version is: g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44)

Again, to save others future frustration in case they make the same silly mistake and are met with the same seemingly erratic behavior, can anyone cast light on where a function without a return gets its return value from??

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no logic to it, and most C++ compilers should flag it with a warning. It allowed for backward-compatibility to C.

In K&R C, there was no void type, and when a type was unspecified, it default to int. So,

myfunc() {....}

Was techincally a function returning a int, but most programmers used that form for a routine not returning a value.

The compiler had to make sense of this. So, the convention became, the return would put something into a register. And the assignment in the calling routine would take the value out of the register. Now, if the callee never issued a return, nothing specific would be placed in that register. But it would still have some (random) value in it, which would be blindly assigned in the caller.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...