what is the difference between outside the main function and inside? - c++

So I have seen a program from elsewhere and the declaration is outside from the main function.
Just like this code:
#include<iostream>
using namespace std;
int num1, num2;
int *ptr1 = &num1, *ptr2 = &num2;
char operation, answer;
char *ptrop = &operation;
int main(){
}
But what I am using right now is inside the main function like this:
#include<iostream>
using namespace std;
int main(){
int num1, num2;
int *ptr1 = &num1, *ptr2 = &num2;
char operation, answer;
char *ptrop = &operation;
So what is the difference from it?

In the first case variables and pointers are accessible from all other functions in the file (i.e. it has global scope) whereas in the second case it is only accessible from within main.
I will give you a small example.
Local to main,
#include <iostream>
void fun();
int main(void) {
int x;
fun();
return 0;
}
void fun() {
x = 1; // compiler error: x not declared in this scope
}
Global,
#include <iostream>
void fun();
int x;
int main(void) {
fun();
return 0;
}
void fun() {
x = 1; // compiles as x declared globally
}

All variables declared outside of the main function will have global scope and static storage duration. Variables declared inside main will have automatic storage duration (allocated on the stack) if no storage specifier is provided and will only be visible inside main.

Related

Variable declaration in C++ within namespaces

In a library I am working with some variables are declared like that:
char &ns::x = y;
However, if I do it that way I get the following error:
error: no member named 'x' in namespace 'ns'
If I rewrite it, it works:
namespace ns {
char &x = y;
}
What exactly is the difference? And why is it working within the library?
If you’re right and the code from the library is exactly as written, then this implies that elsewhere in this library, you’ll find the following declaration:
namespace ns {
extern char& x;
}
In other words, x must have already been declared (and not defined!) inside ns.
The first declaration
char &ns::x = y;
assumes that the name x is already declared in the namespace ns. However this assumption is wrong (in the provided code snippet there is no previous declaration of the variable. Possibly the code snippet is not complete.).
The code snippet can works provided that the variable x is already declared (without its definition) in the namespace ns.
For example
#include <iostream>
namespace ns
{
extern char &x;
}
char y;
char & ns::x = y;
int main() {
return 0;
}
In this code snippet
namespace ns {
char &x = y;
}
there is defined a reference that is initialized by the object y.
The Variable declaration using namespace:
#include <iostream>
using namespace std;
// Variable created inside namespace
namespace first
{
int val = 500;
}
// Global variable
int val = 100;
int main()
{
// Local variable
int val = 200;
// These variables can be accessed from
// outside the namespace using the scope
// operator ::
cout << first::val << '\n';
return 0;
}

Are C++ function declarations optional?

I just noticed something when creating functions. In the code:
#include <iostream>
using namespace std;
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
it will work because the function being called is on top of the caller, but if I put the function add() below the calling function in main() it won't work.
#include <iostream>
using namespace std;
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b = 20)
{
int r;
r = a + b;
return (r);
}
and the compiler will tell me that the identifier add() cannot be found.
so why do we declare functions anyway? like this:
#include <iostream>
using namespace std;
int add(int a, int b = 20);
int main()
{
int result;
result = add(20);
cout<<result;
return 0;
}
int add(int a, int b)
{
int r;
r = a + b;
return (r);
}
A definition is implicitly a declaration. And a declaration must come ahead of the use.
All functions need to be declared before they are used.
You can do that by either (1) writing a declaration, or (2) writing a definition.
Relying solely on (2) can be tempting but then you are bound to order your program in a particular way, and is occasionally impossible. For example, the following will not compile unless the comment is removed.
//void bar(int);
void foo(int n)
{
if (!n){
bar(n);
}
}
void bar(int n)
if (n){
foo(n);
}
}
int main()
{
foo(1);
}
No.
If the function definition appears before the function call, then prototype is not mandatory. Otherwise function prototype is necessary to let compiler know how to respond to a function when it is called.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
if the function definition appears after the function call then prototype is mandatory. because it tells the compiler to how to respond the function when it is called.
check the following example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int, int); // function prototype
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
and if the function definition is made before the function call then it is not mandatory to declare function prototype.
consider example.
/* C++ Function Prototype and C++ Function Definition */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int add(int x, int y) // function definition
{
int res;
res = x + y;
return res;
}
void main()
{
clrscr();
int a, b;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\nSummation = "<<add(a, b);
getch();
}

Obtain variables in function from other function C++

I am trying to pass a variable from one function to another. I have tried this approach but it is not working for me:
int c (){
int x1,x2,y2,y1;
system("cls");
cout<<"Insert Value"<<endl
cin>>x1;
return x1;
}
int cd()
{
int a;
a=c();
cout<<"X1: "<<a;
}
Any help is appreciated. Thanks!
There are a few problems with your code.
First of all you are missing a semicolon after the cout statement in your c() function.
Also you have indicated that function cd() should return an int but you are not returning anything.
Lastly, these function will not begin execution unless you call them explicitly.
Try this:
#include <iostream>
using namespace std;
int c (){
int x1,x2,y2,y1;
cout<<"Insert Value"<<endl;
cin>>x1;
return x1;
}
int cd(){
int a;
a=c();
cout<<"X1: "<<a;
return a;
}
int main()
{
int x=cd(); //call the function to create the side effects
return 0;
}

User-declared namespace member

There is from 3.4.1/14:
If a variable member of a namespace is defined outside of the scope of
its namespace then any name that appears in the definition of the
member (after the declarator-id) is looked up as if the definition of
the member occurred in its namespace.
If that name treated as the definition of the member name then what is it point of declaration?
And why the following example will works:
namespace N
{
extern int j;
}
int i = 2;
int N::j = i; //N::j=2
int N::j=i actual appears into the namespace scope. Hence the declarationint i=2 is not visible for unqualified name lookup. Why does this declaration found?
Your question:
int N::j=i actual appears into the namespace scope. Hence the declaration int i=2 is not visible for unqualified name lookup. Why does this declaration found?
Answer:
Since i is not found in the N namespace, it is looked up in the global namespace. Had an i been there in the N namespace, that would have been used to initialize N::j.
Hope the following program clarifies your doubt.
#include <iostream>
namespace N
{
extern int j;
extern int k;
int x = 3;
}
int x = 2;
int y = 10;
int N::j = x; // N::x is used to initialize N::j
int N::k = y; // ::y is used to initialize N::k
int main()
{
std::cout << N::j << std::endl;
std::cout << N::k << std::endl;
}
Output:
3
10
Update, in response to comment by OP
What the standard is saying is that:
namespace N
{
extern int j;
}
int x = 2;
int N::j = x;
is equivalent to:
namespace N
{
extern int j;
}
int x = 2;
namespace N
{
int j = x;
}
The logic for lookup ofx is same. If it is found within the same namespace N, it is used. If x is not found in namespace N, it is searched for outward in the enclosing namespaces.
You seem to be confused about how name lookup works on a basic level. Maybe a simple example helps:
#include <iostream>
void print(std::string const & s) { std::cout << "Boo: " << s << "\n"; }
namespace Foo
{
std::string message = "Foo";
void action() { print(message); }
}
int main() { Foo::action(); }
Clearly the name print is visible in the definition of Foo::action. Names from containing namespaces are visible in contained namespaces. There's nothing unusual about that.
The point of the rule you are quoting, and which R Sahu already demonstrated nicely, is that you can put the definition of a variable elsewhere from its declaration, and in that case any name appearing in the initializer is looked up in the namespace in which the variable is declared. Here's another example:
namespace Foo
{
namespace Bar { int a = 10; }
int b = 20;
extern int c;
}
namespace Bar { int a = -20; }
int b = 5;
int Foo::c = Bar::a + b; // uses Foo::Bar::a and Foo::b, NOT ::Bar::a or ::b
int main() { return Foo::c; } // returns 30

Accessing member of an unnamed namespace when the outer namespace has a member with the same name

Here is the test code
extern "C" {int printf(const char *, ...);}
namespace PS
{
int x = 10; // A
// some more code
namespace {
int x = 20; // B
}
// more code
}
int main()
{
printf("%d", PS::x); // prints 10
}
Is there any way to access inner(unnamed) namespace's x inside main?
I dont want to change code inside PS. Apologies if the code looks highly impractical.
P.S: I tend to use the name x quite often.
No. The only way to specify a namespace is by name, and the inner namespace has no name.
Assuming you can't rename either variable, you could reopen the inner namespace and add a differently-named accessor function or reference:
namespace PS {
namespace {
int & inner_x = x;
}
}
printf("%d", PS::inner_x);
One way is to add this code:
namespace PS
{
namespace
{
namespace access
{
int &xref = x;
}
}
}
and then you can access what you want:
std::cout << PS::access::xref << std::endl; //prints 20!
Demo : http://ideone.com/peqEs