In the following code, why must int nInteger be declared inside int readNumber()'s body, but int nAnswer must be declared inside the () portion of void writeAnswer()? Declaring int nInteger inside the () or declaring int nAnswer inside the function body causes the IDE to complain about too few arguments for said function. Why does this happen?
I'm using Code::Blocks and the included MinGW on a Windows 7.
#include <iostream>
int readNumber()
{
using namespace std;
cout << "Please enter an integer: ";
int nInteger;
cin >> nInteger;
return nInteger;
}
void writeAnswer(int nAnswer)
{
using namespace std;
cout << "The sum is: " << nAnswer << endl;
}
int main()
{
int x;
int y;
x = readNumber();
y = readNumber();
writeAnswer(x+y);
return 0;
}
So basicly the int readNumber() function does not require any argument to be passed. You declare a local variable so the function knows where to assign the value you type in. You declare variable int nInteger and then in the very next line you assign a value to it by calling cin >> nInteger. If there was no variable declared then your program wouldn't know where to store the value that you type in.
You can think of it as of a basket for apples. You have one basket but no apples in it, then someone gives you 2 apples that you put into the basket. In the end the return statement work like you give the basket to someone else.
Function void writeAnswer on the other hand requires an argument to be passed. As you can see there in local variable declared. What it does is to simply display "The sum is: PASSED_ARGUMENT". So basicly if you call your writeAnswer function with number 6 like writeAnswer(6) it will write "The sum is: 6".
Related
I have been trying to include the declaration of the variable in the function itself but it doesn't work unless I include it in the main function. Why does this happen?
#include<iostream>
using namespace std;
function1(int x)
{
int x =1;
cout << x << endl;
return 0;
}
int main ()
{
function1( x);
return 0;
}` `
Welcome to the world of C++ coding! Looks like there's more than a few issues in the code here - let's break it down and see what we can find.
First and foremost, to answer your original question, your declaration of x (in function1) was made outside of the function you tried to use the variable in (in main). C++ can't normally see variables you declare in one function when it's running in another; that's by design, and is called scope.
To start, the code won't compile for a number of reasons, first and foremost the presence of stray backticks in your code at the very end. These need to be removed.
int main ()
{
function1( x);
return 0;
}` ` //<-- the ` ` will make the compiler angry
Now let's have a look at what's causing the error: x isn't yet declared. In C++, a variable has to be "declared" before it can be used. Since "x" hasn't been declared before its use in function( x);, the compiler kicks it back since it doesn't know what "x" means. Try this:
int x = 0;
function1( x);
We're not quite done yet, though. Once we make this change, the compiler will throw another error: In function 'int function1(int)': 8:5: error: declaration of 'int x' shadows a parameter. You've already included an int x in the definition of function1; by creating another int x inside function1, you've steamrolled your original x. Let's change that from a definition to an assignment.
function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
Getting clsoer, but we've got one more error: 6:16: error: ISO C++ forbids declaration of 'function1' with no type [-fpermissive]. THis is telling you function1 needs to have a return type, which is a keyword in front of the function's name that tells the compiler what type of data it returns (void if it doesn't return any). Looks like you're using return 0; - why not return an int?
int function1(int x)
Now, at last, we've got code that compiles and runs.
#include<iostream>
using namespace std;
int function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
int main ()
{
int x = 0;
function1( x);
return 0;
}
Try it here!
Good luck!
Why does this happen?
It happens because x is now undefined in the context where you're using it in main, and it's already defined (as a parameter) in the context where you're trying to define it in function1().
In the first case, you'll definitely get an error because x as used in main is completely undefined... the compiler is going to look at that function1(x) call and wonder what the heck it's supposed to supply for the x.
In the latter case, the compiler might let you redefine x, but it'll probably at least issue a warning. Also, if it's allowed, then your function1() will always print out 1 regardless of what you pass in for the x parameter because the newly declared x will be used instead of the value passed in the parameter.
The concept that you're missing is called scope. Every variable has a scope, which is essentially the realm in which it's known. The scope of a variable can be global, in which case it's available to the entire program, or limited to a single file, or it can be declared inside a function or block, in which case it's local to that block of code.
int x = 12; // x is available anywhere in the file and has initial value 12
void foo(int x)
{
cout << x << endl; // prints the value passed to foo by the caller
int x = 34; // this new x hides the parameter and is available
// anywhere inside this function, but not outside
cout << x << endl; // prints the new x, i.e. 34
{
cout << x << endl; // still prints 34
int x = 97; // hides the previous x, available only within
// this block or sub-blocks
cout << x << endl; // prints 97
} // x from the enclosed block goes out of scope
cout << x << endl; // prints 34, because we're back to the x at function scope
}
Understanding scope is very important because variable names are often duplicated, either on purpose or by accident, and you need to be able to tell where a given variable is in scope and therefore valid to use, and when it's not.
I want to access the value assigned to global variable in main function from the function. I don't want to pass argument in function.
I have tried referring different stack overflow similar questions and C++ libraries .
#include <iostream>
long s; // global value declaration
void output() // don't want to pass argument
{
std::cout << s;
}
int main()
{
long s;
std::cin >> s; // let it be 5
output()
}
I expect the output to be 5 but it shows 0.
To access a global variable you should use of :: sign before it :
long s = 5; //global value definition
int main()
{
long s = 1; //local value definition
cout << ::s << endl; // output is 5
cout << s << endl; // output is 1
}
Also It's so simple to use global s in cin :
cin >> ::s;
cout << ::s << endl;
Please try it online
You are declaring another variable s in your main function. line 7 of your code. and it's the variable which is used in cin. either delete that line or use :: before s.
long s;
cin >> ::s; //let it be 5
output();
It is important for you to know that the local variable s declared in main() and the variable s declared at file scope aren't identical despite the name.
Since the local variable s declared in the function main() shadows (see Scope - Name Hiding) the global variable s you have to use the Scope Resolution Operator :: to access the global variable s declared at file-scope:
#include <iostream>
long s;
void output()
{
std::cout << s; // no scope resolution operator needed because there is no local
} // s in output() shadowing ::s
int main()
{
long s; // hides the global s
std::cin >> ::s; // qualify the hidden s
output()
}
... or get rid of the local s in main().
That said using global variables (without real need) is considered very bad practice. See What’s the “static initialization order ‘fiasco’?. While that doesn't affect PODs it will bite you sooner or later.
You can do simply and use:: before the global variable or just remove the
long s;
From main() because as you are declaring local variable s in the main() function. The Global s and local s are different despite having the same name. lets learn more by the following example by giving local and Global variable different name.
#include <iostream>
long x; // global value declaration
void output() // don't want to pass argument
{
std::cout << x;
}
int main()
{
long s;
std::cin >> s; //here you are storing data on local variable s
output() // But here you are calling global variable x.
}
In main() function s is local and x is global variable and you are calling the global variable in output() function. you can use:: (scope resolution operator) for calling global x in main if u have the same naming or just call as it by variable name if they have a different name.
PS: If you have any question just do comment down hope this will help you and understand what's the mistake. Read more about the scope of the local and global variable here
You defined output() on the global scope which means it will refer to the long s variable on the global scope not the long s defined in main().
First of all, when you declare a global variable without assigning a value it automatically sets it's value to 0.
And another thing, you should know about your scope. The variable s in your main function has no existence in the output function.
In the output function , you are getting 0 because your global variable is set to 0.
You can just change you global variable's value by assigning different value to it.
long s; //global value declaration
void output() //don't want to pass argument
{
cout<<s;
}
int main()
{
cin>>s; //let it be 5
output()
}
#include <iostream>
using namespace std;
int main()
{
struct calcvaribles;
{
int a;
int b;
int sum;
};
struct introstructions;
{
char ab[35];
string ac;
};
introstructions outline;
outline.ab = "welcome to my calculator program!";
outline.ac = "please enter any [One] number in the
terminal";
return 0;
}
Error message:
aggregate main()::introstructions outline had incomplete type and cannot be defined
Introstructions outline.
Why are you declaring structs inside main? Just move them into
global scope.
You cannot assign a string literal to a char array as you do here: outline.ab = "welcome to my calculator program!";. Instead, use a const char* or, better yet, as you showed below the char array declaration, std::string, but don't forget to #include <string>.
The problem in your code is that you include a ; after the struct name:
struct calcvaribles;
struct introstructions;
The following should work:
#include <iostream>
#include <string>
using namespace std;
int main() {
struct calcvaribles {
int a;
int b;
int sum;
};
struct introstructions {
string ab;
string ac;
};
introstructions outline;
outline.ab = "welcome to my calculator program!";
outline.ac = "please enter any [One] number in the terminal";
return 0;
}
In this situation the C++ language does not help you since the compiler interprets the code in a completely different way than you expect it.
#include <iostream>
using namespace std;
int main()
{
struct calcvaribles;
Because of the semicolon at the end of the above line, the compiler reads this as:
There is a struct called calcvaribles. It's not clear at this point which fields the struct has, that's to be defined elsewhere. In any case, the struct's name is already known, and if you declare a variable of type pointer to that struct, that's allowed from no on.
{
This opening brace means:
A new scope starts here. Any variable that is declared in this scope will only be available until the corresponding }.
int a;
int b;
int sum;
Instead of being struct fields (what you intended), these are declarations of normal variables. These variables don't do anything, they have no values assigned and their values are not read at all. In summary, these three lines are a big "do nothing" block.
};
The scope ends here. From no on, the variables a, b and sum are no more.
The semicolon is useless as well. It's an empty statement. Allowed but useless.
struct introstructions;
{
char ab[35];
string ac;
};
introstructions outline;
outline.ab = "welcome to my calculator program!";
outline.ac = "please enter any [One] number in the
terminal";
return 0;
}
The same happens with the introstructions type.
Had you written the struct definitions outside of the main function, the compiler would have given you a "syntax error" message. Maybe you did that first, and to fix the error message, you moved everything into the main function.
It's unfortunate that only because of these trailing semicolons, the code you wrote still compiled but means something entirely different. But there's no workaround for that.
So I am calling a function which takes input as limit i, and array of objects h.
#include<iostream>
#include<vector>
using namespace std;
class hotel
{
private:
string name,add;
char grade;
int charge,no;
public:
void getdata();
void putdata();
void grade_print(int,hotel[]);
void room_charge();
void top2();
};
void hotel::getdata()
{
cout<<"Add Name: ";
getline(cin>>ws,name);
cout<<"Add Addres: ";
getline(cin>>ws,add);
cout<<"Enter grade,room charge and no. of rooms: ";
cin>>grade>>charge>>no;
}
void hotel::putdata()
{
cout<<name<<endl<<add<<endl<<grade<<endl<<charge<<endl<<no;
}
void hotel::grade_print(int num,hotel h[])
{
int i,j,k; char val;
for(i=0;i<num;i++)
{
val=h[i].grade;
for(j=0;j<num;j++)
{
if(h[j].grade==val)
{
cout<<h[j].grade<<endl;
h[j].grade=' ';
}
}
}
}
int main()
{
std::vector <hotel> h(1);
int i=0,j;
cout<<"Want to add hotel? Press 1: ";
cin>>j;
while(j==1)
{
h[i].getdata();
h.resize(2);
i++;
cout<<"Want to add more? Press 1 for yes, 0 for no: ";
cin>>j;
}
grade_print(i,h);
}
error here is showing that the grade_print is out of scope. Also the grade is a private member but is called by member function. So why is it showing that grade can't be called. Please tell me why so and what can I do to fix it?
Edit1: Declaring function as static void is not helping as the compiler is showing function can't be declared as static void.
D:\C++ Programs\testfile.cpp|30|error: cannot declare member function 'static void hotel::grade_print(int, hotel*)' to have static linkage [-fpermissive]|
From what I can understand, grade_print prints out information about a group of hotels passed as a parameter. If you have a function that acts on a group of a certain class, that function should not be a member of that class. Instead, it should just be a function not associated with any class. This also fixes your scope problem, as it would then have global scope.
If my argument seems weird, think about it like this. Let's say I have a class called number, as well as a function called print_nums which prints an array of numbers passed to it. Would I make print_nums a global function, or a member of the class number? The first one, right? The second one, although it would work, just doesn't really make sense.
grade_print(i, h);
A non-static member function should be called on a specific object like :
h[i].grade_print(i, h);
But, In your case grade_print have to be static, so it should be declared like this:
static void grade_print(int,hotel []);
And the definition goes like normal.
Also, after making grade_print static, you have to call it like this:
hotel::grade_print(i, h);
My plan was to make a simple addition calculator, and move on from there.
Remember, this is my first day coding.
#include <iostream>
#include <string>
using namespace std;
int a;
int b;
int sum;
string ans;
class CalcClass{
public:
int add (int a, int b) {
cout << "Pick the numbers you want to add" << endl;
cin >> a >> b;
sum = a + b;
return sum;
}
};
Added string ans; (at the top). Now I'm getting an "error: no matching function for call to 'CalcClass::add()'"
Why would it be saying this if I already created calcObject and used calcObject.add(); to call the function?
void pickFunction(){
cout << "What Function do you want to do? \n Add, Subtract, multiply, or divide? ";
cin >> ans;
if (ans == "add"){
CalcClass calcObject;
calcObject.add();
}
int main(){
pickFunction();
cout << "Your answer is : " << sum << endl;
return 0;
}
ans needs a type (probably string), add needs quotes ("add"), CalcClass.calcObject; needs to be CalcClass calcObject;.
'dot' syntax (x.y) is used for accessing data or functions that are stored inside of an object, not a class (e.g. calcObject.add(); rather than CalcClass.add();).
Also, as Mahesh says, pickFunction(); needs to be in main. This should look as follows:
void pickFunction(){
//code
}
int main() {
pickFunction();
//...
}
CalcClass.calcObject;
is not the way to create an object. . operator should be used to access object's members/methods. So, create an object like -
CalcClass calcObject;
Also forward declaration of a class isn't useful if object instantiation takes place before compiler can see the definition. So, make sure compiler sees CalcClass before the pickFunction(). With that said, you have to call the pickFunction from main for your program to do anything useful.
Pick a book from The Definitive C++ Book Guide and start reading.