why does this recursion program work? - c++

#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

Related

Returning input in C++

I'm very new to C++ and was wondering if there was a way to return integer input from a function directly without storing it in a variable.
To be more clear:
#include <iostream>
int function()
{
std::cin >> (return function here???)
}
int main()
{
int number = function()
std::cout << number
return 0;
}
Thanks for any help.
if there was a way to return integer input from a function directly without storing it in a variable.
There is not. All standard input interfaces take an object argument which they modify rather than return the resulting value1.
A possible reason for this design is that it is very typical for input to be bad. Only way to avoid returning an int from a function declared to return int is to throw (or terminate the process, but that would be silly). And input error is perhaps considered so non-exceptional that using exceptions for control flow of input handling may be considered inappropriate. This is just my reasoning, not an authoritative explanation for the design choice.
If you fix your function to be correct, with the variable that is necessary and checking for errors, then you can use that function to do exactly that:
return function();
1 With the exception of std::istream::get() and the corresponding C style std::getc and std::fgetc which you can use to extract a single character that they return directly.

Pre increment and post increment when put together on a single variable like this (++i)++, it works in c++ but not in c

I initialized a variable i with a value 3, then put a statement (++i)++ in my code. But, in C, it is showing an error "lvalue required as increment operand". But, if I put this similar code in c++, it works and showing double increment with an output 5. However, one of my friends tried on his compiler using c and it gave an output 4.
//using c
#include <stdio.h>
int main()
{
int i=3;
(++i)++;
printf("%d",i);
return 0;
}
//using c++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i=3;
(++i)++;
cout << i << endl;
return 0;
}
I am using GNU GCC compiler.
This is known to be undefined behavior. Syntactically this program is correct in C++, and the compiler produces some binary code... but the standard allows it to produce ANY code, even something that returns 100 or formats your disk. In real situations you may observe very strange abnormal scenarios, for example the compiler can drop the whole code after your (++i)++ statement, because the standard allows it to do whatever it wants right after the program enters into the status of UB. In your case that would mean that there would be no output at all (or the program would print "Hello World" instead of the integer value).
I believe that you are just conducting an experiment. The result is: both your compiler and your friend's are correct.

Don't we have to assign return values of the functions to variables? C/C++

I've been using C/C++ for about three years and I can't believe I've never encountered this issue before!
This following code compiles (I've just tried using gcc):
#include <iostream>
int change_i(int i) {
int j = 8;
return j;
}
int main() {
int i = 10;
change_i(10);
std::cout << "i = " << i << std::endl;
}
And, the program prints i = 10, as you might expect.
My question is -- why does this compile? I would have expected an error, or at least a warning, saying there was a value returned which is unused.
Naively, I would consider this a similar case to when you accidentally forget the return call in a non-void function. I understand it's different and I can see why there's nothing inherently wrong with this code, but it seems dangerous. I've just spotted a similar error in some very old code of mine, representing a bug which goes back a long time. I obviously meant to do:
i = change_i(10);
But forgot, so it was never changed (I know this example is silly, the exact code is much more complicated). Any thoughts would be much appreciated!
It compiles because calling a function and ignoring the return result is very common. In fact, the last line of main does so too.
std::cout << "i = " << i << std::endl;
is actually short for:
(std::cout).operator<<("i =").operator<<(i).operator<<(std::endl);
... and you are not using the value returned from the final operator<<.
Some static checkers have options to warn when function returns are ignored (and then options to annotate a function whose returns are often ignored). Gcc has an option to mark a function as requiring the return value be used (__attribute__((warn_unused_result))) - but it only works if the return type doesn't have a destructor :-(.
Ignoring the return value of a function is perfectly valid. Take this for example:
printf("hello\n");
We're ignoring the return value of printf here, which returns the number of characters printed. In most cases, you don't care how many characters are printed. If compilers warned about this, everyone's code would show tons of warnings.
This actually a specific case of ignoring the value of an expression, where in this case the value of the expression is the return value of a function.
Similarly, if you do this:
i++;
You have an expression whose value is discarded (i.e. the value of i before being incremented), however the ++ operator still increments the variable.
An assignment is also an expression:
i = j = k;
Here, you have two assignment expressions. One is j = k, whose value is the value of k (which was just assigned to j). This value is then used as the right hand side an another assignment to i. The value of the i = (j = k) expression is then discarded.
This is very different from not returning a value from a non-void function. In that case, the value returned by the function is undefined, and attempting to use that value results in undefined behavior.
There is nothing undefined about ignoring the value of an expression.
The short reason it is allowed is because that's what the standard specifies.
The statement
change_i(10);
discards the value returned by change_i().
The longer reason is that most expressions both have an effect and produce a result. So
i = change_i(10);
will set i to be 8, but the assignment expression itself also has a result of 8. This is why (if j is of type int)
j = i = change_i(10);
will cause both j and i to have the value of 8. This sort of logic can continue indefinitely - which is why expressions can be chained, such as k = i = j = 10. So - from a language perspective - it does not make sense to require that a value returned by a function is assigned to a variable.
If you want to explicitly discard the result of a function call, it is possible to do
(void)change_i(10);
and a statement like
j = (void)change_i(10);
will not compile, typically due to a mismatch of types (an int cannot be assigned the value of something of type void).
All that said, several compilers (and static code analysers) can actually be configured to give a warning if the caller does not use a value returned by a function. Such warnings are turned off by default - so it is necessary to compile with appropriate settings (e.g. command line options).
I've been using C/C++ for about three years
I can suppose that during these three years you used standard C function printf. For example
#include <stdio.h>
int main( void )
{
printf( "Hello World!\n" );
}
The function has return type that differs from void. However I am sure that in most cases you did not use the return value of the function.:)
If to require that the compiler would issue an error when the return value of a function is not used then the code similar to the shown above would not compile because the compiler does not have an access to the source code of the function and can not determine whether the function has a side effect.:)
Consider another standard C functions - string functions.
For example function strcpy is declared like
char * strcpy( char *destination, const char *source );
If you have for example the following character arrays
char source[] = "Hello World!";
char destination[sizeof( source )];
then the function usually is called like
strcpy( destination, source );
There is no sense to use its return value when you need just to copy a string. Moreover for the shown example you even may not write
destination = strcpy( destination, source );
The compiler will issue an error.
So as you can see there is sense to ignore sometimes return values of functions.
For your own example the compiler could issue a message that the function does not have a side effect so its call is obsolete. In any case it should issue a message that the function parameter is not used.:)
Take into account that sometimes the compiler does not see a function definition that is present in some other compilation unit or in a library. So the compiler is unable to determine whether a function has a side effect,
In most cases compilers deal with function declarations. Sometimes the function definitions are not available for compilers in C and C++.

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.

Which default argument is evaluated first and why?

I have three functions, funt1(), funt2(), and funt3().
int funt1()
{
cout<<"funt1 called"<<endl;
return 10;
}
int funt2()
{
cout<<"funt2 called"<<endl;
return 20;
}
void funt3(int x=funt1(), int y=funt2())
{
cout << x << y << endl;
}
My main function:
int main()
{
funt3();
return 0;
}
When I am calling funt3() in my main() method, why is funt1() is called first, and then funt2()?
It depends on your compiler. Others may call funct2() first. Neither C or C++ guarantee the order of evaluation of function arguments.
See Parameter evaluation order before a function calling in C
C++ standard does not define that, so it's totally compiler-specific. That said, you should never rely on an instance of undefined behaviour.
EDIT: if you really want to keep functions invocations as default parameters to reduce the numbers of parameters you have to pass each time I suggest you do the following:
void funt3(int x, int y)
{
cout<<x<<y<<endl;
}
void funt3(int x)
{
funt3(x, funt2());
}
void funt3()
{
funt3(funt1());
}
The language does not require any particular order. The order used will be compiler dependent.
Compiler specific and from there it goes down to the CPU. CPU might branch that call into separate branches, it might try to do some predictions, or if the CPU thinks func1 is way faster than func2 it will run func1 and a bunch of other operations before func2 so it optimizes.
As C++ standard doesn't define the order so it's depend on compiler.
You can simply try a few popular c++ compilers: GCC, VS2008/VS2010 etc.
Then you will see totally different result.
compiler dependent. it maybe funt1 then funt2 then funt3 or any other combination.
As noted by everybody else, the order of evaluation of function parameters is unspecified by the C++ standard. This allows each compiler to choose an optimal order, whether that order is determined by convenience or efficiency.
You may even find that the order can change based on the optimization flags you give to your compiler.
In order to guarantee the sequence of the function calls you need to introduce a sequence point between the calls. I accomplish this below by creating two different versions of the function, so that only one function call is made as a parameter.
void funt3(int x, int y=funt2())
{
cout << x << y << endl;
}
void funt3()
{
int x = funt1();
funt3(x);
}
It is because the parameters of funt3(sp?) needs to work out x then y. i.e. funt1() then funt2() before considering the contents of funt3.