Why doesn't this C++ function need return? - c++

I saw some one write this code
int r, odd_divisors(int a, int b) {
r = sqrt(b) + 1;
r -= sqrt(a);
}
AFAIK, the compiler will automatically add return 0; at the end of this code, but in this case, it returns the value of r. Could someone please help me to explain why this happen. Thanks.
UPDATE:
This function actually works in this Codefights site: https://codefights.com/challenge/eu4zLJDcv88B2mcCp. You can check for sir_ementaler's solution.
UPDATE 2:
Thanks for everyone that pointed out this function is ill format. I knew that. The reason I asked here is because it is the winner's solution in the site I mentioned in the previous update. It looks to me that Codefights must add some other feature to their compiler.

The "implicit int" rule that you may know from pre-standard C does not apply to C++.
This is invalid code.
Fix your broken code.

The code you posted is not legal C++, but it is very close to legal. The following is legal:
// Example program
#include <iostream>
#include <string>
#include <math.h>
int r, odd_divisors(int a, int b);
int odd_divisors(int a, int b) {
r = sqrt(b) + 1;
r -= sqrt(a);
return 0;
}
int main()
{
odd_divisors(16,25);
std::cout << "Hello, " << r;
}
There are two things going on here. Firstly, you can define an int and declare a function in the same statement, but you can't define the function. Allowing this is an obvious compiler extension.
Secondly, failing to return a value from a value-returning function is undefined behaviour. That can mean a crash - but it can also mean doing exactly what you expect. If you don't try to use the value from the function, it is quite likely (but not certain), that nothing very much will happen.
It is of course, much cleaner to make odd_divisors be a void function, or better still, make it return the value and not use a static at all.

Related

Namespaced Functions interfering with print

I'm new to the site and browsed several similar sounding questions but haven't found my exact problem. I suspect I'm making elementary mistakes. A link to an answer would be appreciated, or an explanation, and again I'm sorry if my question doesn't even match the title of the post.
For c++ on the Cxxdroid app for android and in Visual Studio C++:
I'm trying to experiment with classes and namespaces to provide flexible utility to the class. I want to use different implementations of the same function for personal analysis of certain algorithms on data structures; namely arrays vs lists/trees and also between recursive and iterative implementations of standard procedures. I know how to do asymptotic analysis but my stubborn mind wants real numbers.
Unfortunately, however, I can't even seem to get namespace functions to work without blowing up normal functionality. Please note, I haven't learned c++ formally yet because I'm exploring ahead of my introductory c/c++ course.
For example:
#include <iostream>
namespace iterative{
int power(int base,int expo){...}
}
namespace recursive{
int power(int base,int expo){...}
}
int main(int argc,char* argv[]){
int result = 0;
int num = 3;
int exp = 2;
//Expecting 9 in result
std::cout << "This prints fine" << std::endl;
result = iterative::power(num,exp);
std::cout << result;
std::cout << " This number and text doesn't print" << std::endl;
return 1;
}
I had a much more complex function with classes above the namespaced functions (search function for node classes inside a list/tree class) but it never worked. Then I just threw together the above snippet and tried to print result but the std::cout never fired after my function call.
Can anyone offer insight into what I'm doing wrong here? The first cout prints and the second wont. Further, execution hangs during the function call; the solution keeps running until I force it to stop.
I've tried to comment out one of the namespaces while using the other.
I've tried the using keyword with the namespace_name.
I've tried passing integers without variable usage: result = power(3,2);
I've tried printing the function result directly: std::cout << power(3,2) << std::endl;
I can't seem to get it to work on either application. I know this seems like a silly and simple question but after about a week of browsing the internet I'm inundated with very vague answers to questions regarding syntax. Perhaps I'm just not connecting the dots to my own problem...
Is my syntax in definition wrong?
Is my syntax in calling the function wrong?
Is my syntax in variable assignment wrong?
I'm at my wits' end.
Edit:
Now I feel really stupid.
You were correct. I didn't increment my variable in the iterative implementation, which meant it hung up on an infinite loop. I had to print the loop to see the numbers spitting out like I'm Neo in The Matrix. Unfortunately, I didn't test the recursive function because it felt dangerous to do so if I couldn't even get the iterative function to call first...
I was so focused on using namespaces for the first time that I never looked at the loop properly.
Thank you, and sorry for the bother. I'm going to try to extend this experiment to namespace-defining class member functions now.
Edit2: Feel free to delete this...unless it's felt that my stupidity can help others.
Silly mistake was made:
...
int power(int base,int expo){
int i = 0;
int retval = 1;
while( i < expo ){
retval *= base;
//Never did i++; or i = i + 1;
//Had to std::cout << retval; in loop to catch it
}
return retval;
}
...

Confused regarding this statement about "function call by reference."

What I'm confused about is whether the question is asking about passing arguments to functions as references (as opposed to "Call by Value") or about how we can set a pointer to point to a function.
The exact question is:
"Explain the function call by reference giving a suitable example in support of your answer."
The way it's termed makes it feel like it's asking about the latter. In my head, it seems as if it's asking how a function is called by reference, i.e, using a pointer.
C++ for what I'm talking about: int (*ptr)(int, int);
Which can later be assigned to a function like int max(int a, int b);
I know this is a bit of an odd post for Stack since it's more of an English question, but it's the only place I could think to ask.
EDIT: A lot of people are asking what I mean by the second thing. Since I'm new to the concept, I'll just copy - paste what my textbook gives as an example: (Sorry for the terrible formatting, sorry!)
main() {
int max(int a, int b){...}; //Your typical maximum function
int (*ptr)(int, int);
ptr = max;
//Then if you want to run the program
m = (*ptr)(2, 5);
cout << m; //Outputs 5
}

What is standard reference to lookup the scope of calls by reference?

First of all here is a snippet of some code that made me feel not quite sure about how reference identifiers work:
#include <iostream>
using namespace std;
void theUgly (int *z, int *q)
{
if(q == z)
*z=3;
/*else*/
*z=6;
};
void theNice (int &y, int *q)
{
theUgly(&y, q);
};
int main()
{
int x = 5;
theNice(x, &x);
cout << x << endl;
}
I wasn't sure to expect output be 3 or 5 since I wasn't sure about reference running with 2 identifiers having the 2 address, what seemed odd to me, or just leaving this handling to the user.
But I actually got 6 as output, what now lets me assume there is compiled in some kind of atomic operations.
I tried to find the exact documentation about this behavior in my "n3690" copy of the c++11 standard. I found the most part I was able to look up was dealing with capture reference declarations or other stuff named capture or lambda expressions. But just a handful of times I was able to strg+f "by reference" in it. And nothing really seemed to me like explaining the mechanic that describes the behaving of my snippet.
So my question simply is: Where exactly in the c++11 standard it is described, how a program has to handle the parameters and scopes, as happened for my test snippet?
EDIT:
After noticing and adding the missing else the snippet puts out what I would expect. But since I wasn't able to find any information about the behaving of passes by refference in the standard docs, The question remains as it is, independed of the snippet.
Your *z=6; is not in an else clause. This assignment is executed in any case.
Actually, g++-5.3 -O2 -std=c++14 transforms theNice into:
void theNice (int &y, int *q)
{
y = 6;
};
As for the behaviour of references as functions arguments:
[dcl.fct]: function parameter declaration
[dcl.init.ref]: initialization of references
[expr.call]: initialization of function parameters with argument expressions
In short: They behave like local references and reference (alias) the (l)value they are bound to. Calling a function which expects a (lvalue) reference with a (l)value binds that reference to the provided value in the scope of the callee.

why does this recursion program work?

#include <iostream>
using namespace std;
int main() {
int n,x;
int fact(int);
cin >> n;
x = fact(n);
cout << x;
return 0;
}
int fact(int n) {
if(n!=1)
return n*fact(n-1);
}
In the last case, when the argument passed to the function fact is 1, how is it able to calculate that fact(1) is equal to 1, without me specifying it in my code?
This program relies on undefined behavior. It is certainly not guaranteed to work, but you may have found a situation in which the parameter you send (1) is in a place where the calling code perceives it as the return value. Do not depend on this behavior.
Many C++ compilers would reject this code as having a semantic issue: Not all control paths return a value from fact()
int fact(int n);
This function signature returns an integer, but when n=1 is given there is no corresponding return statement in your implementation. In that case, the function may return any int value (i.e. garbage in memory) and the behaviour is undefined. You should not depend on this, even though your compiler allows it to run.
I'm quite certain you saw a warning when compiling your program. In my environment (g++ on Mac OSX), the compiler issued the following warning:
warning: control may reach end of non-void function [-Wreturn-type]
Personally, I don't think there is any good reason for a compiler to allow this kind of bug (i.e. it should fail to compile).
Reference: A similar question is found below:
C++ return value without return statement

Unexpected output

#include <iostream>
int main()
{
const int i=10;
int *p =(int *) &i;
*p = 5;
cout<<&i<<" "<<p<<"\n";
cout<<i<<" "<<*p;
return 0;
}
Output:
0x22ff44 0x22ff44
10 5
Please Explain.
Well, your code obviously contains undefined behaviour, so anything can happen.
In this case, I believe what happens is this:
In C++, const ints are considered to be compile-time constants. In your example, the compiler basically replaces your "i" with number 10.
You've attempted to modify a const object, so the behavior is
undefined. The compiler has the right to suppose that the const
object's value doesn't change, which probably explains the
symptoms you see. The compiler also has the right to put the
const object in read only memory. It generally won't do so for
a variable with auto lifetime, but a lot will if the const has
static lifetime; in that case, the program will crash (on most
systems).
I'll take a shot at it: since there's no logical reason for that output, the compiler must have optimised that wretched cout<<i<<" " to a simple "cout<<"10 ". But it's just a hunch.