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.
Related
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.
This question already has answers here:
Why is it that we can write outside of bounds in C?
(7 answers)
Is accessing a global array outside its bound undefined behavior?
(8 answers)
Undefined, unspecified and implementation-defined behavior
(9 answers)
Closed 11 months ago.
I wrote a code for entering element and displaying the array at the same time. The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements? Code:
#include <iostream>
using namespace std;
void display(char arr[],int n)
{
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
return;
}
int main()
{
char A[4];
int i=0;
char c;
for(;;)
{
cout<<"Enter an element (enter p to end): ";
cin>>c;
if(c=='p')
break;
A[i]=c;
i++;
display(A,i);
system("clear");
}
return 0;
}
Writing outside of an array by using an index that is negative or too big is "undefined behavior" and that doesn't mean that the program will halt with an error.
Undefined behavior means that anything can happen and the most dangerous form this can take (and it happens often) is that nothing happens; i.e. the program seems to be "working" anyway.
However maybe that later, possibly one million instructions executed later, a perfectly good and valid section of code will behave in absurd ways.
The C++ language has been designed around the idea that performance is extremely important and that programmers make no mistakes; therefore the runtime doesn't waste time checking if array indexes are correct (what's the point if the programmers never use invalid ones? it's just a waste of time).
If you write outside of an array what normally happens is that you're overwriting other things in bad ways, possibly breaking complex data structures containing pointers or other indexes that later will trigger strange behaviors. This in turn will get more code to do even crazier things and finally, some code will do something that is so bad that even the OS (that doesn't know what the program wants to do) can tell the operation is nonsense (for example because you're trying to write outside the whole address space that was given to the process) and kills your program (segfault).
Inspecting where the segfault is coming from unfortunately will only reveal what was the last victim in which the code is correct but that was using a data structure that was corrupted by others, not the first offender.
Just don't make mistakes, ok? :-)
The code works but since char A[4] is static memory why does not it terminate/throw error after entering more than four elements?
The code has a bug. It will not work correctly until you fix the bug. It really is that simple.
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?
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a stack overflow error?
look the code below.
#include <iostream>
using namespace std;
void leave(double as){
cout<<as;
leave(as);
}
int main(){
double x=1234.5;
leave(x);
cout<<"hellow";
}
When this code executes their is no way to stop. it should print the value x over and over again. But practically, this works for about 20 secs and close automatically. It doesn't print the line hellow. What is the reason for it? In windows task manager I can realize that the memory used with the application will increase. but I have allocated memory for x within the main function only, so will the function allocate memory for x over and over again. Is this type of situation called a memory leak? if its so what lines should be added to prevent it?
If I change the code as below it shows the word hellow without going through the function over and over again:
void leave(){
leave();
}
int main(){
leave();
cout<<"hellow";
}
How to explain these situations?
Every call to leave() results in adding a little information to the stack. When you call it recursively, the stack grows until it runs out of space, and the operating system terminates the application. In the second example, presumably the compiler optimized out the function that did nothing.