A reason to forbid recursive call of main() in C++ [duplicate] - c++

This question already has answers here:
Why calling main() is not allowed in C++
(3 answers)
Why are recursive main() calls not allowed in C++? [duplicate]
(2 answers)
Closed 2 years ago.
C++ standard says:
The function main shall not be used within a program.
Also:
Recursive calls are permitted, except to the main function.
At the same time C allows such a usage of main according to this answer. I found a comment under that answer that says the following:
The simplest implementation of global constructors (without special support from the OS and underlying C runtime entry code) is for the C++ compiler to generate a function call at the beginning of main (__main is a common name for it) which calls all the global constructors. Having global objects be reconstructed every time main gets called recursively would be a rather bad thing... :-)
It makes sense, but I've tried the following code:
#include <cstdio>
struct S {
S() { std::puts("S ctor"); }
~S() { std::puts("S dtor"); }
};
S s;
int main() {
static int count = 0;
count++;
if (count <= 10) {
std::printf("%d ", count);
return main();
}
std::puts("");
}
in clang, gcc, msvc. All of these compilers print same output:
S ctor
1 2 3 4 5 6 7 8 9 10
S dtor
So the global s object was contructed only once despite recursive call of main. Yes, I know what are undefined/unspecified/implementation-defined behaviour mean. But would someone explain (or even demonstrate by code for any available in internet compiler) in more details why using a main function in the C++ program is forbidden and may lead to unexpected results in particular?

Related

the cpp return value without defining [duplicate]

This question already has answers here:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
(11 answers)
Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?
(2 answers)
warning as Control reaches at the end of a non-void function when implementing binary search
(2 answers)
Closed 3 months ago.
enter image description here
i don't know that why this cpp program is returning the value without defining the return value
i was expecting that this program will return will print the error value
#include <iostream>
using namespace std;
int sum(int a)
{
int c = a + 1; // this fucntion is returning value of c without defining
}
int main()
{
cout << sum(25);
return 0;
}
Welcome to the world of undefined behavior if you declare a function to return a value, but do not explicitly do so. The function may appear to work, or it may do something else.
This also applies if a function has a return, but control flow means it isn't reached. For instance, in the following simple function.
int foo(bool b) {
if (b) {
return 42;
}
}
Turn on and pay attention to compiler warnings.

implicit default value for class member variable? [duplicate]

This question already has answers here:
How do C++ class members get initialized if I don't do it explicitly?
(8 answers)
Closed 1 year ago.
I'm doing C++ tests for my certification exam and I came across this exercise that i don't understand:
(the question is what is the output of the following program)
#include <iostream>
using namespace std;
class A {
public :
float v;
float set(float v) {
A::v += 1.0;
A::v = v+1.0;
return v;
}
float get(float v){
v +=A::v;
return v;
}
};
int main()
{
A a;
cout<< a.get(a.set(a.set(0.5)));
return 0;
}
I expected to have an error on the first line of the set function since A::v was never initialized, but my program compiles and it seems that A::v has value 0 by default..
Could someone please explain why there is no compilation error?
Like you mentioned, the first line of set used A::v, which was never initialized before. However, that itself doesn't produce an error, it is undefined behavior. What it means is the compiler may initialize it for you, or it might just pickup a random number it sees on the memory, or whatever they are pleased to. The C++ standard doesn't say what needs to happen, so it left the compiler to decide whatever is easy.
However, whatever happens on that line shouldn't matter too much in your code, in most cases. The reason is A::v will be re-assigned to v + 1 on the next line. So it should almost always print 2 at the end.

Return value in C++ [duplicate]

This question already has answers here:
C++ return value without return statement
(6 answers)
Closed 6 years ago.
I am confused with the following output in C++
int add()
{
int c = 2+3;
}
int main()
{
int x = add();
cout << x;
return 0;
}
This prints 5.even if we do not write return statement.
How this is managed in C++.
Please help.
This is UB. You're right to be confused - this can work one day and fail the next. Don't rely on undefined behavior.
If you want to know why it works, it's because parameters & return values are passed on a data structure called stack (well - usually; sometimes passed in the same register). Similarly, most implementations use this same stack for locals. Therefore, the int in add will be located in the same place as where the return value is expected (by your specific implementation) and your implementation doesn't invalidate memory when your int there is destructed. But it's still destructed, it's still UB and it might break in any second.
As the comments wrote, you might turn on warnings to avoid this kind of error.

C++ scopes and allocation [duplicate]

This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 6 years ago.
If I understand correctly, variables that are not dynamically allocated are supposed to be deleted at the end of their scope.
However, I wanted to try it out with this code (which I think is not correct as I am supposed to use dynamic allocation) :
int* function()
{
int a = 3;
return &a;
}
int main(int argc, char const *argv[]) {
int* a(function());
std::cout << *a << std::endl; // prints 3
}
Why can I still access the value of the variable a by using the pointer returned by the function when it is supposed not to exist anymore ?
a and hence the return value from function has gone out of scope. You are just lucky.
Just be careful and compile with all the warnings enables - and take heed of those warnings.
The fact that you can access the value is pure luck. The code has undefined behaviour (since the variable is destroyed) and the compiler can generate whatever it wants - but you cannot rely on it.

Recursive call on main C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can main function call itself in C++?
I found this problem very interesting but illusive a bit.
Question 6.42 C++ how to program by Dietel "Can main be called recursively on your system? write a program containing a function main. Include Static local variable count and initialize to 1. Post-increment and print the value of count each time main is called. Compile your program. What happens ?
I wrote the program as below but instead I made the recursion stops after 10 times as if I were to keep it running it will stops at a value around 41000.
my question: how is it legal to call recursively main function in c++, should this program be executed to stack over flow or memory fault, etc.. ? Please explain.
#include <iostream>
using namespace std;
int main()
{
static int count = 0;
count++;
if(count <= 10) {
cout << count << endl;
return main(); //call main
}//end if
system("pause");
return 0;//successful completion
}//end main
thank you
How is it legal to call the main() function recursively in C++
It is not legal. The C++ language standard states that "The function main shall not be used within a program" (C++11 ยง3.6.1/3). Calling the function is a form of "use."
Any program that calls main() exhibits undefined behavior (technically, such a program is ill-formed because the rule being violated is a diagnosable semantic rule, though I'd be surprised if most compilers rejected the program). Note that this does not prevent the runtime infrastructure that starts your program from calling the main() function.