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;
}
Printable View
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.Quote:
Also, how could I used the "x" of main() in add()?
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;
}
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.
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.