I got an error, saying that the "x" in the add function is not declared. It is legal in C, but not in C++. May i know why? Also, how could I used the "x" of main() in add()?Code:int main() int x = 5; int add(int a, int b) { return a+b+x; }
I got an error, saying that the "x" in the add function is not declared. It is legal in C, but not in C++. May i know why? Also, how could I used the "x" of main() in add()?Code:int main() int x = 5; int add(int a, int b) { return a+b+x; }
err...Where is main() 's body?
Do you really think this code is legal in C?
Pass it by reference.Also, how could I used the "x" of main() in add()?
Last edited by manasij7479; 07-31-2011 at 03:20 AM.
Sorry, i was typing an example without realising that i didnt put the braces for the main().
By the way, can i have a simple example based on this exampleCode:int main() { int x = 5; int add(int a, int b) { return a+b+x; } }
C is not pascal. One consequence is that functions cannot be implemented inside the bodies of other functions.
Why in C, there is no problem calling a variable from main() in add(), where add() is inside main()? Why is it illegal is C++?
The closest you can come to that is..
Code:#include<iostream> int main() { int x = 5; int add(int,int,int&); std::cout<<add(2,4,x)<<std::endl; std::cout<<x; //To show that x really changes } int add(int a, int b, int& x) { x-=4; return a+b+x; }
Last edited by manasij7479; 07-31-2011 at 04:44 AM.
If this code is legal for you, then your C compiler is brain-dead. Put it out of our misery and get a new one.
Disclaimer: This post shows my ignorance at the time of its making. I claim ownership of but not responsibility for all errors in it. Reference at your own peril.
Thanks for the reply, I got it.
GCC allows nested functions.
Using and Porting the GNU Compiler Collection (GCC): C Extensions
Why it does is another matter entirely.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.