A function is a sequence of statements designed to do a particular job. You already know that every program must have a function named main(). However, most programs have many functions, and they all work analogously to main.
Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life all the time. For example, you might be reading a book when you remember you need to make a phone call. You put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your book where you left off.
C++ programs work the same way. A program will be executing statements sequentially inside one function when it encounters a function call. A function call is an expression that tells the CPU to interrupt the current function and execute another function. The CPU “puts a bookmark” at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.
Here is a sample program that shows how new functions are declared and called:
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std; // we need this in each function that uses cout and endl
cout << "In DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std; // we need this in each function that uses cout and endl
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() In DoPrint() Ending main()
This program begins execution at the top of main(), and the first line to be executed prints Starting main(). The second line in main is a function call to DoPrint. At this point, execution of statements in main() is suspended, and the CPU jumps to DoPrint(). The first (and only) line in DoPrint prints In DoPrint(). When DoPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next statment executed in main prints Ending main().
Functions can be called multiple times:
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std;
cout << "In DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std;
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
DoPrint(); // This is a function call to DoPrint()
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() In DoPrint() In DoPrint() In DoPrint() Ending main()
In this case, main() is interrupted 3 times, once for each call to DoPrint().
Main isn’t the only function that can call other functions. In the following example, DoPrint() calls a second function, DoPrint2().
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
void DoPrint2()
{
using namespace std;
cout << "In DoPrint2()" << endl;
}
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std;
cout << "Starting DoPrint()" << endl;
DoPrint2(); // This is a function call to DoPrint2()
DoPrint2(); // This is a function call to DoPrint2()
cout << "Ending DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std;
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() Starting DoPrint() In DoPrint2() In DoPrint2() Ending DoPrint() Ending main()
Return values
If you remember, when main finishes executing, it returns a value back to the operating system (the caller) by using a return statement. Functions you write can return a single value to their caller as well. We do this by changing the return type of the function in the function’s declaration. A return type of void means the function does not return a value. A return type of int means the function returns an integer value to the caller.
// void means the function does not return a value to the caller
void ReturnNothing()
{
// This function does not return a value
}
// int means the function returns an integer value to the caller
int Return5()
{
return 5;
}
Let’s use these functions in a program:
cout << Return5(); // prints 5 cout << Return5() + 2; // prints 7 cout << ReturnNothing(); // This will not compile
In the first statement, Return5() is executed. The function returns the value of 5 back to the caller, which passes that value to cout.
In the second statement, Return5() is executed and returns the value of 5 back to the caller. The expression 5 + 2 is then evaluated to 7. The value of 7 is passed to cout.
In the third statement, ReturnNothing() returns void. It is not valid to pass void to cout, and the compiler will give you an error when you try to compile this line.
One commonly asked question is, “Can my function return multiple values using a return statement?”. The answer is no. Functions can only return a single value using a return statement. However, there are ways to work around the issue, which we will discuss when we get into the in-depth section on functions.
Returning to main
You now have the conceptual tools to understand how the main() function actually works. When the program is executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating system. This is why main is declared as int main().
Some compilers will let you get away with declaring main as void main(). Technically this is illegal. When these compilers see void main(), they interpret it as:
int main()
{
// your code here
return 0;
}
You should always declare main as returning an int and your main function should return 0 (or another integer if there was an error).
Parameters
In the return values subsection, you learned that a function can return a value back to the caller. Parameters are used to allow the caller to pass information to a function! This allows functions to be written to perform generic tasks without having to worry about the specific values used, and leaves the exact values of the variables up to the caller.
This is a case that is best learned by example. Here is an example of a very simple function that adds two numbers together and returns the result to the caller.
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// add takes two integers as parameters, and returns the result of their sum
// add does not care what the exact values of x and y are
int add(int x, int y)
{
return x + y;
}
int main()
{
using namespace std;
// It is the caller of add() that decides the exact values of x and y
cout << add(4, 5) << endl; // x=4 and y=5 are the parameters
return 0;
}
When function add() is called, x is assigned the value 4, and y is assigned the value 5. The function evaluates x + y, which is the value 9, and then returns this value to the caller. This value of 9 is then sent to cout to be printed on the screen.
Output:
9
Let’s take a look at a couple of other calls to functions():
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
int add(int x, int y)
{
return x + y;
}
int multiply(int z, int w)
{
return z * w;
}
int main()
{
using namespace std;
cout << add(4, 5) << endl; // evalutes 4 + 5
cout << add(3, 6) << endl; // evalues 3 + 6
cout << add(1, 8) << endl; // evalues 1 + 8
int a = 3;
int b = 5;
cout << add(a, b) << endl; // evaluates 3 + 5
cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
return 0;
}
This program produces the output:
9 9 9 8 7 6
The first three statements are straightforward.
The fourth is relatively easy as well:
int a = 3;
int b = 5;
cout << add(a, b) << endl; // evaluates 3 + 5
In this case, add() is called where x = a and y = b. Since a = 3 and b = 5, add(a, b) = add(3, 5), which resolves to 8.
Let’s take a look at the first tricky statement in the bunch:
cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
When the CPU tries to call function add(), it assigns x = 1, and y = multiply(2, 3). y is not an integer, it is a function call that needs to be resolved. So before the CPU calls add(), it calls multiply() where z = 2 and w = 3. multiply(2, 3) produces the value of 6, which is assigned to add()’s parameter y. Since x = 1 and y = 6, add(1, 6) is called, which evaluates to 7. The value of 7 is passed to cout.
Or, less verbosely (where the => symbol is used to represent evaluation):
add(1, multiply(2, 3)) => add(1, 6) => 7
The following statement looks tricky because one of the parameters given to add() is another call to add().
cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
But this case works exactly the same as the above case where one of the parameters is a call to multiply().
Before the CPU can evaluate the outer call to add(), it must evaluate the inner call to add(2, 3). add(2, 3) evaluates to 5. Now it can evaluate add(1, 5), which evaluates to the value 6. cout is passed the value 6.
Less verbosely:
add(1, add(2, 3)) => add(1, 5) => 6
Effectively using functions
One of the biggest challenges new programmers encounter (besides learning the language) is learning when and how to use functions effectively. Functions offer a great way to break your program up into manageable and reusable parts, which can then be easily connected together to perform a larger and more complex task. By breaking your program into smaller parts, the overall complexity of the program is reduced, which makes the program both easier to write and to modify.
Typically, when learning C++, you will write a lot of programs that involve 3 subtasks:
- Reading inputs from the user
- Calculating a value from the inputs
- Printing the calculated value
For simple programs, reading inputs from the user can generally be done in main(). However, step #2 is a great candidate for a function. This function should take the user inputs as a parameter, and return the calculated value. The calculated value can then be printed (either directly in main(), or by another function if the calculated value is complex or has special printing requirements).
A good rule of thumb is that each function should perform one (and only one) task. New programmers often write functions that combine steps 2 and 3 together. However, because calculating a value and printing it are two different tasks, this violates the one and only one task guideline. Ideally, a function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value.
Quiz
1) What’s wrong with this program fragment?
void multiply(int x, int y)
{
return x * y;
}
int main()
{
cout << multiply(4, 5) << endl;
return 0;
}
2) What’s wrong with this program fragment?
int multiply(int x, int y)
{
int product = x * y;
}
int main()
{
cout << multiply(4, 5) << endl;
return 0;
}
3) What value does the following program fragment print?
int add(int x, int y, int z)
{
return x + y + z;
}
int multiply(int x, int y)
{
return x * y;
}
int main()
{
cout << multiply(add(1, 2, 3), 4) << endl;
return 0;
}
4) Write a function called doubleNumber() that takes one integer parameter and returns double it’s value.
5) Write a complete program that reads an integer from the user (using cin, discussed in section 1.3), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.
Quiz Answers
To see these answers, select the area below with your mouse.
1.5 — A first look at operators
|
Index
|
1.3 — A first look at variables (and cin)
|
1.5 — A first look at operators
Index
1.3 — A first look at variables (and cin)
I noticed you include this comment we need this in each function that uses cout and endl when you include namespace std;.
Why do you include the library locally as opposed to globally? Are there functions in the library that conflict with other libraries that would cause a problem? Is it just a matter of preference? I hope I am not getting ahead of myself here.
That’s a very good question, actually.
Just as with local/global variables, it’s better to declare things at a local scope if you can (and it’s not too onerous). It reduces the chance of inadvertently changing something you didn’t mean to, or having a name clash.
While this is rarely a problem in small programs, in gigantic programs that run ten or hundreds of thousands of lines of code, your odds of having a strange name clash go up significantly.
Probably the safest solution is to not use a “using” statement at all, and explicitly call the function with it’s namespace qualifier:
std::cout << “Hello world!” << std::endl;
But that makes for some ugly, harder to read code (and I haven’t covered the scope qualifier yet!). Using a using statement at the function level is a nice compromise between safety and readability.
Well, in this case, can’t we merge libraries together? and then obviously if u can do that the computer will automatically detect duplicated function names, even if it can’t, you would manually be able to sort it out
One problem I noticed with your source code for question number 5 is that you cannot use double as a function name, at least in Visual Studio 2005, as double is a reserved word. Changing it to Double allows it to work.
I may be wrong for other compilers, but I think that double is a reserved word in most CPP builds.
Thanks, Jim. You are absolutely right. I changed the function name.
That’s one advantage of using function names that begin with capital letters instead of lowercase — it avoids conflicts with language keywords.
shouldn’t there be the cin.ignore(); statement after cin >> xxx; ? if I use the source code like in solution to question 5, the program terminates after I give in the number and press enter.
Sandor, that’s a compiler dependent issue. Some compilers close the output window immediately upon termination, while others (such as Visual Studio) hold it open until the user presses a key.
If your compiler immediately closes the output window, then for any console program you will need to add a line of code that waits for a keystroke before exiting. There are many different ways to do this.
I typically use
cin.get();i use visual basic and when i type:
#include
#include
int double(int x)
{
return 2 * x;
}
int main()
{
using namespace std;
int x;
cin >> x;
cout —— Build started: Project: helloworld, Configuration: Debug Win32 ——
1>Compiling…
1>helloworld.cpp
1>c:\documents and settings\samuel ac\my documents\c++\helloworld\helloworld\helloworld\helloworld.cpp(4) : error C2632: ‘int’ followed by ‘double’ is illegal
1>c:\documents and settings\samuel ac\my documents\c++\helloworld\helloworld\helloworld\helloworld.cpp(4) : error C2062: type ‘int’ unexpected
1>c:\documents and settings\samuel ac\my documents\c++\helloworld\helloworld\helloworld\helloworld.cpp(5) : error C2143: syntax error : missing ‘;’ before ‘{’
1>c:\documents and settings\samuel ac\my documents\c++\helloworld\helloworld\helloworld\helloworld.cpp(5) : error C2447: ‘{’ : missing function header (old-style formal list?)
1>Build log was saved at “file://c:\Documents and Settings\Samuel AC\My Documents\C++\helloworld\helloworld\helloworld\Debug\BuildLog.htm”
1>helloworld – 4 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Hi Sam. Double is a keyword in C++, and it shouldn’t be used as a function name. I’d previously updated question 4 to address this issue, but I missed the same issue for question 5. It’s fixed now.
These tutorials are fantastic :]
Fox is right :)
Why is this not working?
Ignore the include blank thing, I dont know why its doing that, I have iostream after that, this thing keeps erasing it..
The problem is that you have a semicolon after
Remove the semicolon and it should work as expected.
u see there is your problem
it should be like this
there was a space between the first two”<”
and at end you should write
system ("pause");if you use console
It will surely work dude!
#include "stdafx.h" #include <iostream> //including iostream library int multiply(int a,int b) { return a * b; } int main() { using namespace std; cout << multiply(1001,8) << endl; return 0; }I am trying to do the last question. Using code::blocks i have come up with this:
#include
#include
int main()
{
int doPrint()
{
int doublenumber(int x=5)
return 2*x;
}
I’m confused. please tell me what i’m doing wrong.
Josh, please put your code in PRE html tags, otherwise, it gets treated as HTML rather than C++ code.
There are two problems here: First, it looks like you’ve declared int doublenumber(int x=5) correctly, but you’ve done so inside doPrint(). Replace doPrint() with your doublenumber declaration. Second, you’ve declared your functions inside other functions, which C++ does not allow. Place your functions above main().
what’s the tag?
<PRE>code here</PRE>
Great tutorials thus far. Question on Quiz #5 for you. Your solution obviously works fine:
int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; int x; cin >> x; cout < < doubleNumber(x) << endl; return 0; }But — when I do my solution, which is basically the same as yours but listed in a different order:
int main(){ using namespace std; int x; cin >> x; cout < < doubleNumber(x) << endl; return 0; } int doubleNumber(int x){ return 2 * x; }I get a compiler error in MS Visual Cpp 2008 Express [error C3861: 'doubleNumber': identifier not found].
Now, when I move my “doubleNumber(int x)” function so it appears ABOVE “main()” like so:
int doubleNumber(int x){ return 2 * x; } int main(){ using namespace std; int x; cin >> x; cout < < doubleNumber(x) << endl; return 0; }it works fine. So my question is: I thought the placement of “main()” within the code isn’t supposed to matter? I thought I read that somewhere in your tutorials… But regardless where I think I saw that, it doesn’t make sense that “main()” would have to appear at the bottom of every piece of Cpp code. Am I overlooking something?
Thx,
-Dan
Dan, when the compiler compiles your program, it reads through the files sequentially. This means if it hasn’t encountered doubleNumber() by the time you try to use doubleNumber(), then it will give you an error.
There are two ways to fix this:
1) Put your functions above main()
2) Use a function prototype. This means, put the function declaration
int doubleNumber(int x);above main(), and leave the actual function definition below main(). That way, when the compiler encounters doubleNumber(), it will know what to expect, even if you haven’t actually defined how doubleNumber() is implemented yet.Thanks for the feedback, Alex. I understand what you’re saying.
So generally speaking, when Cpp developers write their code, (the assumption I’m making here is that) they’re always putting their functions above “main()”? I would think that, by doing your fix #2 — i.e. using a function prototype for every function — that would create a lot of extra lines of code, especially when you get into software that has thousands of lines of code.
So the practice among Cpp developers is to have “main()” defined at the bottom of all Cpp code?
When developing single-file programs, yes. But when you get into multi-file programs, things become a bit more complex. In the case of multi-file programs, the typical way of doing this is to put the function prototypes in a header file, and then #include the header file wherever you need access to those functions. I cover this in more detail in section 1.9.
i’m dong question 5 how you said. At the moment it looks like this:
#include
int doublenumber(int x)
{
return 2*x;
}
int main ()
{
using namespace std;
int x;
cin >> x;
cout
But all I get when I run and build it is the hello world program.
I keep writing these things but it never does what i want it to.
Would you happen to know why it is doing this and how the problem could be solved?
It sounds to me like you’re compiling and executing the wrong program. Many IDEs let you have multiple projects open simultaneously — however, only one project will be active/selected, and this is the one that will compile/execute. Make sure you have your doublenumber project active. Usually active projects have their names in bold.
sorry, I cant get the PRE tags to work.
Hmmm, that’s bizarre. They have been working for other people in this thread (eg. Dan). They seem to work for me okay too:
What browser/OS are you using?
windowa 2000. Dont know what IE i’m using.
I’ve managed it in Dev-c and it runs ok but when I type in a number it doesn’t double.
My code is same as the solution.
Without seeing your code I couldn’t say what the problem is. Since you’re having issues with the pre tags, try posting your code in my forum and I’ll address your issue there.
OK then I’ve signed up to the forums. Which thread is it or do I make a new one?
Make a new thread in the “For Beginners” section.
I think these are absolutely great tutorials, certainly the best I’ve ever found. Please keep up the great work Alex!
I feel silly saying this, since I’m just starting out, but shouldn’t quiz questions one through three have
using namespace std;
statements in their main functions since they use cout and endl?
Thanks for the complements, and your question isn’t silly at all. If you wanted to compile these fragments, you’d need to add
using namespace std;as well as#include, but since they’re just code fragments rather than entire programs meant to be compiled I omitted the minor details.Hi Alex,
I was just doing question 5 of the quiz like everyone else, but the problem is that when I input a number the window closes once immediately after it displays the answer. I know you have to add the statements like cin.get(); cin.clear(); and cin.ignore(255, ‘/n’);, however, it does doesn’t prevent it from happening. Heres my coding.
I tried adding cin.get, as I have commented. THANKS
Try:
int main() { int x; cin >> x; x = doubleNumber(x); cout < < x << endl; cin.clear(); cin.ignore(255, '\n'); cin.get(); return 0; }what is the difference between the following declarations
void show()and void show(void)
There is no difference. They are functionally equivalent.
[ I answered your question in my forum. -Alex ]
/* Program to get double value of Number*/
#include <iostream.h>
#include <conio.h>
int doubleNumber(int x)
{
return x * 2;
}
void main()
{
int x;
clrscr();
cout << "n Enter the number : ";
cin >> x;
cout << "n The double value is : "<<doubleNumber(x);
getch();
}
I come from a pretty decent background. I have had 7 years experience in my overall field. I know PHP/Javascript like the back of my hand…I wanted to get into C++ lately and I am working towards it. So far I love the language. The ONE thing I don’t like so far about it is having to put the main function at the bottom (or the other way you mentioned). It seems kind of unnecessary and definitely doesn’t sound like it’ll be very neat and manageable. The hard part is remebring to make a function before that…the one problem I would have is if I had 2 functions that called each other.
In PHP you can have 1 function and then another function and because they are related sometimes each one of the functions ends up calling the OTHER function once. So that leaves you with something you can’t do in C++. You can’t make both functions above each other (impossible) so it won’t work like that.
You actually can have two functions in C++ that call each other. However, to do this, you have to use function prototypes, which we I haven’t covered at this point in the tutorials. I cover this in lesson 1.7.
/pre
After studying your first couple of steps over night this is the code I managed to compile. Mind you I just started last night and never knew a thing about coding until now. I put did a combination of the three tests and heres what I came up with. It was very much enjoyable debugging and learning that the void must come before the main. Only takes one mind to expand a thousand others, thanks Alex much appreciated, cant wait to study further!
________________________________________________
// Test subject.cpp : main project file.
#include “stdafx.h”
#include
using namespace System;
void Test()
{
using namespace std;
cout << “Starting Test 2″ << endl;
cout << “What is the value of X x Y?” <> x;
cin >>y;
cout << “The correct answer is ” << x + y <<endl;
cout << “Testing complete!” <<endl;
system (”pause”);
}
int main()
{
using namespace std;
cout << “Test 1 compiling…” <<endl;
cout << “Compiling complete, starting Test2″ <<endl;
system (”pause”);
Test();
return 0;
}
________________________________________________
somehow in the transferring this typo came up:
cout << “What is the value of X x Y?” x;
should read:
cout << “What is the value of X + Y?” <>y;
cin >>x;
__________
not sure how to embed the code to make it look proper yet, so its still not working apparently
There is no <> operator in C++, so I’m not sure what you’re attempting to do here.
I’m a complete n00b when it comes to programming.. I find it very interested how there are many different ways of getting the same work done.
My answer to question 5 is totally different, but still works: I just think my way could be considered Bloatware. I’ll just have to learn how to be
more effecient.
int doubleNumber(int x, int y)
{
return x * y;
}
int main()
{
using namespace std;
int x = 2; //multiplier
int y;
cout <> y; // read number from console and store it in y
cout << y <<” doubled equals ” << doubleNumber(x, y) << endl;
return 0;
}
Anyway, I love your tutorials. I tried learning Pascal from a text book. I gave up before the first chapter. I think I might have a change using your tutorials,
Thanks!
#include
int doubleNumber(int x)
{
using namespace std;
cout <> x;
return x * 2;
}
int main()
{
using namespace std;
cout << “The number is: “; cout << doubleNumber(2) << endl;
return 0;
}
So.. I’m having trouble.. “Enter the # to be doubled: ” and “The number is: “; appear together.. How can I make the program wait until a number is received and THEN print “The number is: “
i can’t declare a function; it keeps on saying: expected primary-expression before “int” or before “void”
i’d like to see my previous comment w/ my .c proggie and how ppl rate it. Noobs need reinforcement
PS i’m glad you mentioned “less than/greater than” is not a c++ operator, i couldn’t figure that one out though it would be cool if it worked. Can i # define it and add it to “iostream”?
If you would like to have your code viewed/rated by other people, it’s much better to post it in the forums.
Unfortunately, you can’t define <> as a new operator in C++. If you’re looking to do inequality (which is the only thing I can think of that would make sense for <>), you’ll have to get used to using !=
Nah, the way i saw that operator, , used was to define get a variable (for example from cin, and cout that variable. As Frostbite and Sumanyu did above.
Thank you so much. This tutorial is definitely the best out there!
I’ve gone through quite a few websites looking for tutorials.
This one is by far the best i’ve ever seen.
Alex, you are an amazing teacher. Everything here is clear, and the examples let you put it into practice, give you a template to do your own things with, and the quiz at the end is an excellent self-learning tool to make sure you actually know what you think you do.
Only suggestion I could make would be to perhaps put a few more quizzes into pages that don’t have one ;)
Thanks so much. I’ve been wanting to learn C++ for probably 2 years now. I’ve always had the motivation, but I could never find a tutorial that could get me over that first little step (past the Hello World! program ;)).
~Seltox
I appreciate your comments. I’d definitely like to go back and add more quizzes to the pages that don’t have them, and add more quiz questions to the pages that do. I’ve been prioritizing new content over quizzes, but now that I’m almost done with the initial content set (just have exceptions to do) I will hopefully have time for that soon. Thanks again.
c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘endl’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘endl’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘endl’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘endl’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘endl’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘cout’ : undeclared identifier
1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘endl’ : undeclared identifier
1>Build log was saved at “file://c:Documents and SettingsJoseMy DocumentsVisual Studio 2008ProjectsFunctionsFunctionsDebugBuildLog.htm”
1>Functions – 12 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Any help?
Make sure you do the following at the top of your file (below the stdafx line):
int main() { using namespace std; cout << "enter a number x: "; // where x is any number entered by the user int x; cin >> x; // get x number from the console cout << "you entered "<< x << endl; } int Doublenumber(int x) { return 2 * x; } cout << Doublenumber << x << endl; return 0 system("PAUSE"); return EXIT_SUCCESS; }i am having problems with this code can Alex please can you help
tell me what i am doing wrong thanks
the line cout Double number (
It look like you put your Doublenumber() function right in the middle of your main() function. Functions can’t be nested in C++.
Just move Doublenumber() above main() and you will be one step closer.
Also, when you call Doublenumber, it should be like this: Doublenumber(x)
Whats wrong with my code?
#include "stdafx.h" int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; // we need this in each function that uses cout and endl cout << doubleNumber(5) << endl; // evaluates 5*2 return 0; }these are the errors
1>c:\vc2008projects\doublenumber\doublenumber\doublenumber.cpp(13) : error C2871: ’std’ : a namespace with this name does not exist
1>c:\vc2008projects\doublenumber\doublenumber\doublenumber.cpp(14) : error C2065: ‘cout’ : undeclared identifier
1>c:\vc2008projects\doublenumber\doublenumber\doublenumber.cpp(14) : error C2065: ‘endl’ : undeclared identifier
nvm I forgot #include
If you define the value of x then call a different function will it remember the value of x? Because when I compile my infinitely increasing number loop I get this error:
Here’s the source code:
#include <iostream> using namespace std; void loop() { x = x + 1; cout << x; loop(); } int main() { int x; x = 1; loop(); return 0; }No. If a variable is declared in one function, other functions won’t even know it exists unless you pass it as a parameter.
The reason you are getting an error is because x is declared in main(), so loop() is unaware of it’s existence.
Thanks so much for taking the time to make this tutorial!
This was my answer to 4/5:
#include "stdafx.h" #include <iostream> int doubleNumber(int x) { return x * 2; } int main() { using namespace std; cout << "Double this: "; int x; cin >> x; int y = x; cout << y <<" + "<< y <<" = "<< doubleNumber(x) << endl; return 0; }Peace be upon you
It’s good place to learn and good exam
However it’s my answer for question number 5
#include <iostream> // Function to double the "d" int doubleNumber( int d ) { return d + d ; } int main() { using namespace std ; int x ; // Declare an integer to read from the user cout << "Please enter a number to double it" << endl; cin >> x ; cin.ignore() ; cout << "You entered" << endl ; cout << x << endl ; // Take the input "x" from user to double it by function doubleNumber cout <<"Duplicated your number is" << endl ; cout << doubleNumber(x) << endl ; return 0 ; }that was my way
#include <iostream> int main() { using namespace std; int x; cin >> (x); cout<< (x*2)<<endl; system ("pause"); return 0; }waiting critics…this is my first day in c++
In the beggining of this tutorials page you start of with DoPrint functions and you do a great job explaing it. all the sample code is complete and ready to compile. when i reach the Return Values and Parameters examples you have incomplete code that cannot compile? Why wasnt it written in complete ready to compile form?
// add takes two integers as parameters, and returns the result of their sum // add does not care what the exact values of x and y are int add(int x, int y) { return x + y; } int main() { // It is the caller of add() that decides the exact values of x and y cout << add(4, 5) << endl; // x=4 and y=5 are the parameters return 0; }This gives me an error because u do not define X and y!!?
1>—— Build started: Project: HelloWorld, Configuration: Debug Win32 ——
1>Compiling…
1>HelloWorld.cpp
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘endl’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘endl’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘endl’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘endl’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘endl’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘cout’ : undeclared identifier
1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘endl’ : undeclared identifier
1>Build log was saved at “file://c:\C++2008\HelloWorld\HelloWorld\Debug\BuildLog.htm”
1>HelloWorld – 12 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
What gives? Am I an idiot? Or is there a reason y u didnt write the code out completely?
If you look at the errors your compiler is telling you, it’s not complaining about x and y, it’s complaining that it doesn’t know what cout and endl are. In order to define those, you have to #include and use the “using namespace std;” line.
I fixed the example and made it a complete program so it will compile.
Alex Sir,
I have been observing that whenever you are calling a function,
the function been called has been declared earlier in the program.
Is there any specific reason that a function been called has to be
present before it is been called…
I mean to say that,
If i call a function named “doprint2()” from a function;
“doprint1()” and the function “doprint1()” has been coded before
the function “doprint2()”. And then, i call the function would it affect
it anyway..
A function must be declared prior to it’s use. However, it does not necessarily need to be defined before use.
In all these examples I declare and define the functions before they are used because it keeps the examples easy. However, in future lessons, you will learn how to prototype a function so you can both use it and define it anywhere you want.
Alex Sir,
The following code doesn’t seem to work properly…
It takes in all the instructions and data..but, doesn’t provide me with
the result i.e .. the addition of the two numbers…
plz help..
#include "stdafx.h" #include <iostream> int add(int a, int b) { using namespace std; cout << "The sum of the two numbers is: "; return a+b; } void main() { using namespace std; cout << "Enter Number: "; int x; cin >> x; cout << "you have entered: " << x << endl; cout << endl; cout << endl; cout << "Lets add two numbers: " << endl; cout << "Enter first number: "; int q; cin >> q; cout << endl; cout << "Enter second number: "; int w; cin >> w; cout << endl; add(q,w); }The problem is your function does not print the results of a+b, it just return it to main(), which doesn’t do anything with the result either.
heres my code
#include <iostream> int variable(int x) { return 2 * x; } int main() { using namespace std; cout << "Enter a number and it will be doubled: "; int x; cin >> x; cout << variable(x) << endl; return 0; }can you tell me what is wrong with this int doublenumber(int x, int y) { int x = 7; int y = 2; return x * y; system("PAUSE"); return EXIT_SUCCESS; }Your function terminates at the first return statement it encounters, so it never executes the last two lines.
I was expecting output to be this; Starting Main() In DoPrint() 1 Back in Main() In Test2() 2 Back in Main() Ending Main() Press any key to Continue ... However, I end up getting this; Starting Main() In DoPrint() In DoPrint() 1 Back in Main() In Test2() In Test2() 2 Back in Main() Ending Main() Press any key to continue ... Not sure why? Here is my code. #include <iostream> // Declaration of Function Test2() int Test2() { using namespace std; cout <<"In Test2()"<<endl; return 2; } // Declaration of Function DoPrint() int DoPrint() { using namespace std; cout <<"In DoPrint()"<<endl; return 1; } // Declaration of Main() int main() { using namespace std; cout <<"Starting Main()"<<endl; DoPrint(); cout <<DoPrint()<<endl; cout <<"Back in Main()"<<endl; Test2(); cout << Test2()<<endl; cout <<"Back in Main()"<<endl; cout <<"Ending Main()"<<endl; system("pause"); return 0; }You call DoPrint() twice — once standalone, and once part of the following cout statement. Each time DoPrint() is executed, it prints “In DoPrint()”, which is why you see it twice.
Dude, just declare
before the functions! It works for me. Thanks :)
Can someone tell me what’s wrong with this code:
#include "stdafx.h" #include <iostream> #include <winsock.h> #pragma comment(lib,"ws2_32.lib") int doit(int, char **) { using namespace std; char ac[80]; if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) { cerr << "Error " << WSAGetLastError() << " when getting local host name." << endl; return 1; } cout << "Host name is " << ac << "." << endl; struct hostent *phe = gethostbyname(ac); if (phe == 0) { cerr << "Bad host lookup." << endl; return 1; } for (int i = 0; phe->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr)); cout << "Address " << i << ": " << inet_ntoa(addr) << endl; } return 0; } int IDE(int argc, char *argv[]) { WSAData wsaData; if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { return 255; } int retval = doit(argc, argv); WSACleanup(); return retval; } int StartProgram() { using namespace std; cout << "Starting Program" << endl; return 0; } int main(int argc, char *argv[]) { using namespace std; StartProgram(); IDE(); return 0; }I think you should ask this in the forum, not here.
Normally yes, unless you include a pause statement. Alex pointed out earlier that this is discussed in section 0.7.
My code is exact same as his yet i get an end1 undeclared identifier error
any reasons why? and i dont know to to do those tags but i did include the iostream thing and #
include
void DoPrint2()
{
using namespace std;
cout << “In DoPrint2()” << end1;
}
void DoPrint()
{
using namespace std;
cout << “starting DoPrint()” << end1;
DoPrint2();
DoPrint2();
cout << “Ending DoPrint()” << end1;
}
int main()
{
using namespace std;
cout << “Starting main()” << endl;
DoPrint();
cout << “Ending main()” << end1;
return 0;
}
Mike, it should be endl (end-L), not end1 (end-one), that is probably where the problem is!
hi alex.
I’m doing question 4 and it doesn’t seem to work. i have
#include "stdafx.h" #include <iostream> int doubleNumber(int x) { return 2 * x; }This is my error:
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:\VC2008 PROJECTS\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
1>Build log was saved at “file://c:\VC2008 PROJECTS\HelloWorld\HelloWorld\Debug\BuildLog.htm”
1>HelloWorld – 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
You have to add a main function which calls your function (doubleNumber()), and you should also add using namespace std; after the #include statements. A C++ program cannot (at least I know of no such thing) be run without a main function, because that is the actual function being called by the operating system!
I’m confused by this:
int add(int x, int y, int z) { return x + y + z; } int multiply(int x, int y) { return x * y; } int main() { cout << multiply(add(1, 2, 3), 4) << endl; return 0; }Can you explain how x, y and z are being attributed there. I thought you had to say x = 7 or whatever, but here there’s nothing like that. Is it down to the order you write x, y and z in along with the order of the numbers later on? Or will it just attribute the values to x first, then y, then z, no matter what order you wrote them in (e.g. z, x, y)?
Another repeated comment, no bad intentions. Please see my explanation at the bottom.
When you call the function add(int x, int y, int z), the compiler is expecting 3 integer values within the parentheses, in that exact order, separated by commas. The integer values that are passed this way are in turn assigned to x, y, and z.
Thus, when you write this call: add(1,2,3), it is equivalent to add(x = 1, y = 2, z = 3), and the functions will treat these variables (x y and z) as having those values, as long as the function is running.
In other words, by calling add(1,2,3), you are really giving values to the variables in question, just as it should be.
It helps if you try to think of functions as separate from each other, just like Alex explained: A function returns a value to the caller, and the caller can pass parameters to the function being called. What this means effectively is that x, y and z are variables LOCAL to the function add (not main()!), and main simply helps the function add by telling it what value it should give to its variables.
Hope that helps! Send a mail otherwise (csvanefalk@hushmail.me). Of course, you should also ask Alex, I don’t know how often I will be checking these comments!
After working for a while, i made this. It looks too complicated tho. I had to look at the tutorials a few times to get this done. I was wondering, if there was an easier way to get the same thing done. Because this took me some time to finish lol.
One more thing.
When it said ” cout << “Enter a number: ” << endl; ”
it appears like this.
Enter a number:
5
is there a way to change that number to appear next to the : So when it says Enter a number: we type right next to it instead of under it.
Thanks. And great tutorials. This helped me a lot.
#include "stdafx.h" #include int Multi(int e, int r) { return(e*r); } void Multiply() { using namespace std; int q; cout << "Now Lets multiply two numbers. Enter the first number." <> q; cout << endl; cout << endl; int w; cout << "Enter the second number" <> w; cout << endl; cout << endl; cout << "Your answer is: " << q*w << endl; cout << endl; cout << endl; } int DoubleD(int x) { return(2*x); } int TrippleD(int y) { return(3*y); } int main() { using namespace std; int x; cout << "Enter a number: " <> x; cout << endl; cout << endl; x = DoubleD(x); cout << "Your answer is: " << x << endl; cout << endl; cout << endl; Multiply(); int y; cout << "Enter a number to be trippled" <> y; cout << endl; cout << endl; y = TrippleD(y); cout << "Your answer is: " << y << endl; cout << endl; cout << endl; system("pause"); return 0; }endl means “end line”
if you don’t want to end the line at that point remove endl from the end of the statement.
anything after the endl will be on a new line, including your input.
this keeps the cursor on the same line because you’re not telling it to start a new line after the first cout.
Hi Mike,
forgive me if I am missing something, but I do not see why you keep on using in the cout statements sometimes! This is not even a valid operator for cout, and as such it should give you a compile error (it did for me, I tested it to see if it was simply an operator I have never heard of).
To read a value and store it into a variable, you use cin:
also, you do not need to write a new cout statement for each endl you use, you can put them all in a single statement. For example:
is the same as
As for your question: the trick is simply to avoid putting a newline character (”\n”) or endl at the end of the cout statement preceding the cin statement which will read the value.
In your case, it would look like this:
the output should now be (assuming the user enters 5):
Enter a number: 5
Hope that helps!
edit to my post, the top should read:
“…but I do not see why you keep on using
in the cout statements…”
forgive my repeated comments! But there is obviously something wrong here: I try to comment the post by mike, and instead my reply ends up as a separate comment at the bottom of the list.
[EDIT: I looked at it again, and maybe there is nothing wrong after all, I just mistook schmiggys comment for a separate comment, not a reply, and as such of course my reply to Mike ended up after it. My bad.]
Hi Alex,
Your tutorials are amazing and im going through them and understanding every bit. But where do i put this code?
Let’s use these functions in a program:
Hi Alex,
Just wanted to add my thanks for a great tutorial.
Hi Alex,
I’m having difficulty posting code. Do I have to embed each line of code in HTML tags or simply at the beginning and end of the code?
Apparently either way works!
Just testing posting code!
Hi Alex,
Contrary to your solution to quiz 2, it does compile on my system and prints the correct result. I am using Dev-C++ 4.9.9.2., Did I misunderstand your solution or is there another explanation? The program code follows:
#include int multiply(int x, int y) { int product = x * y; } int main() { using namespace std; multiply(4, 5) << "nn"; << "Double PRESS any KEY to EXIT"; cin.clear(); cin.ignore(255, 'n'); cin.get(); }Thanks Alex!
I compiled my first little program for Quiz Question 5 and it was great: worked like a charm and basically matched your solutions!
But then I showed it off to my girlfriend… She entered an unfathomable positive number in the console (to be doubled), but the result came back negative.
What’s going on to cause this? When I use integers of a smaller magnitude everything seems to work perfectly.
Just curious. –Joe
I may be wrong on this, but I think this is because of “rollover.” in other words, there is a maximum value that can be stored as an integer, and as I read somewhere else, when you perform an operation on a positive integer that makes it larger than the max, it rolls the number over to the smallest number (kinda like an odometer). In the case of integers, its a negative number.
I first learned MATLAB programming, and when you went overboard there, it just returned “inf” for infinity. At least with that I could understand what had happened lol.
i understand thiss all so far but how do i write a program that i can use on a computer without an ide?
Very well explained thanks for these tutorials:) Here is my first program using functions.
#include <iostream> void GotoPoint()//Creates a function called GotoPoint which returns nothing, hence "void". { using namespace std;//Needed for cout and endl. cout << "In GotoPoint()..." << endl;//Prints message to screen, ends line. } int main()//main function needed in every program. { using namespace std;//Needed for cout and endl. cout << "In main()..." << endl;//Prints message to screen, ends line. GotoPoint();//Calls the function GotoPoint(). cout << "Back in main()..." << endl;//Prints message to screen, ends line. cout << "Ending main()..." << endl;//Prints message to screen, ends line. cout << "Press Enter to close program. ";//Prints message to screen. cin.get();//Stops program from closing. return 0; }remember the quiz on the last page, if we [programmers] write an equation 4 a computer to solve how can we make the computer solve the sum asked by the user?
does cout mean ecout like in French
I really hadn’t thought of that. Nice.
Unfortunately Mr. Stroustrup (our beloved c++ father :) ) is not as romantic. cout is simply (c)haracter (out)put
Why doesn’t this work?
#include <iostream> int doubleNumber(int x, int y) { int product = x * y; } int main() { using namespace std; cout << "Enter a number." << endl; int z; cin >> z; cout << doubleNumber(z * 2) << endl; }you used two parameters in doubleNumber function definition, but during function call only one parameter..number of parameters must be same.
and also doubleNumber must return a value.
if you are using Visual Basic then you need the #include “stdafx.h” thing at the beginning. Other wise I don’t know
Hello Karan.
showx() is not a good candidate for a function being redundant (and bad as a technique).
Regarding your comments I’d say they are pretty much wrong. More specifically
we know what cout does so no need to comment it
again your variable declaration is obvious so no need to comment it
we know what cin does.
same as above
These comments could make it :) although they’d be better suited to a bigger and more complex program that has a lot of functions.
One other thing is that you probably should have also commented at the beginning of your doubleNumber function, explaining what does it do.
i have tried the following example in the tutorial but it just doesn’t work., What have missed?
//#include <stdafx.h> // Visual Studio users need to uncomment this line #include <iostream> #include <stdafx.h> void DoPrint() { using namespace std; cout << "In DoPrint()" << endl; } int main() { using namespace std; cout << "Starting main()" << endl; DoPrint(); cout << "Ending main()" << endl; return 0; }The code is alright, so it must be something with your IDE
If you are NOT using Visual Studio, remember to remove stdafx
First of all kudos for the great site you have.
I had a little problem with exercise 5. My solution was this:
#include <iostream> using namespace std; int doubleNumber (int x) { x = x * 2; return x; } int main() { int x = 0; cout << "Please enter a number: "; cin >> x; cout << endl; doubleNumber(x); cout << "The result is " << x; return 0; }The problem is that the value is not doubling. Doing a debug, I saw that the function was called correctly, x was calculated as it should inside the function, but never returned to main. Doing a x=myFunction(x) resolves it, but I don’t understand why? If I’m simply using a myFunction(x) isn’t x supposed to get the new value calculated inside the function?
Hay i am having a problem as whenever i run my console window closes, its annoying me as it is preventing me from learning.
Well, I’m new to this whole programming thing as I started yesterday, but as far as I can read, you’re using
or
and as I see it, it should be
I hope I was right :)
I am trying to learn C++. I just started today, so please don’t say that I suck. I am trying to make a calculator that adds, divides, subtracts and multiplies. Please help me! Any help would be great. the is the code:
// FullCalculator.cpp : Defines the entry point for the console application. // #include <stdafx.h> #include <iostream> int main() { using namespace std; int x; cout << "press 1 for add, 2 for subtract, 3 for multiply, and 4 for divide" << endl; cin >> x; if (x == 1) { add(); } else { notadd(); } } int notadd() { if (x == 2) { subtract(); } else { notsubtract(); } } int notsubtract() { if (x == 3) { multiply(); } else { notmultiply(); } } int notmultiply() { if (x == 4) { divide(); } } int add() { using namespace std; int a = 0; //makes x an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> a; // saves entered number as x int b = 0; //makes y an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> b; // saves entered number as y int c = x + y; // makes c = a + b cout << a << " plus " << b << " equals " << c << endl; // diaplays x plus y = z } int subtract() { using namespace std; int d = 0; //makes d an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> d; // saves entered number as d int e = 0; //makes e an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> e; // saves entered number as e int f = d - e; // makes f = d - e cout << d << " minus " << e << " equals " << f << endl; // diaplays x plus y = z } int multiply() { using namespace std; int g = 0; //makes g an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> g; // saves entered number as g int h = 0; //makes h an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> h; // saves entered number as h int i = g * h; // makes z = x * y cout << g << " times " << h << " equals " << i << endl; // diaplays x plus y = z } int divide() { using namespace std; int j = 0; //makes j an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> j; // saves entered number as j int k = 0; //makes k an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> k; // saves entered number as k int l = j / k; // makes l = j / k cout << j << " divided by " << k << " equals " << l << endl; // diaplays x plus y = z }Here are the errors:
error C3861: ‘add’: identifier not found
error C3861: ‘notadd’: identifier not found
error C2065: ‘x’ : undeclared identifier
: error C3861: ’subtract’: identifier not found
: error C3861: ‘notsubtract’: identifier not found
error C2065: ‘x’ : undeclared identifier
error C3861: ‘multiply’: identifier not found
error C3861: ‘notmultiply’: identifier not found
error C2065: ‘x’ : undeclared identifier
error C3861: ‘divide’: identifier not found
I think the: ‘x’ : undeclared identifier
is happening because the x variable ammount is not being carried over tho the other functions. how would I do this?
BTW, this is a great site. I don’t get the return stuff either.
hi salam nhn calculator main bohat error hn aur coding ho to do plz
im writeing down for example “In DoPrint” bewten the cout and endl but i get red letters insteed of blue ones?? why?? im using visual c++ 2010
i have done everything right
Do you always have to put all your functions above the main function?
Doublepost, sorry
Disregard the above post(s), the 1.7 tutorial explained it.
// 1.4 (4).cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int doubleNumber(int x) { return 2 * x; } int main() { cout << "Input a number to be doubled:" << endl; int x; cin >> x; cout << "The number: " << x << " has been entered" << endl; cout << "Your number has been doubled to: " << doubleNumber(x) << endl; return 0; }The program works fine when I press ctrl+F5 in Visual Studio. But, when I open the application from the directory it is in, it automatically closes instead of me pressing ENTER again.
Not sure how to edit…
Anyways, the same thing happens when I press F5 instead of CTRL+F5 in Visual Studio. Sorry, I’m new to programming. I am opening the program in the debug directory. Maybe that’s why. But where else would the program be? That is the only place where I can find the application file. So, do I have to use Visual Studio every time I want to open my program otherwise the program will close before asking me to press enter again?
I already know Javascript and some normal Java but this is not responding to things like ‘cin’ and ‘end1′ in the ‘iostream’ library. Why?
I have this really wacked question I must have missed something I can’t find Why don’t we put “using namespace std;” on the very top like right after our #includes ?
Hey
just a quick one…
was wondering how i can display text before the input, this is my first go at C++ so any help is good.
Here is what i have come up with so far, but its on the same line.
cheers
int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; cout <> x; cout << doubleNumber(x) << endl; return 0; }so from that to this
int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; cout << "enter number to be doubled" ; int x; cin >> x; cout << doubleNumber(x) << endl; return 0; }Hi Alex,
Should function definition be there before main??? and Why??
when we write a program like this, it will not work
#include “stdafx.h”
#include “iostream”
int main()
{
using namespace std;
int numb,a;
cout << "Enter number" <> numb;
a = doubleNumber(numb);
cout << a;
return 0;
}
int doubleNumber(int x)
{
return x*2;
}
Jil,
In the third line,
should be
.
Also, int main() should be at the bottom of the program. (or write
under the
#include .
I hope that helps.