ch2-Declare (Declaration & definition examples)
Chapter_2 | Hello Exercise_2-1 |
Declare.cpp TCP1, p. 93-94 download
// Declaration & definition examples
#include <iostream> // no semicolon after directive
using std::cout; // console output
using std::endl; // newline
extern int i; // Variable declaration without definition
extern float f(float); // Function declaration
float b; // Variable declaration & definition
float f(float a) // Function definition
{
return a + 1.0;
}
int i; // Variable definition
int h(int x) // Function declaration & definition
{
return x + 1;
}
int main()
{
b = 1.0;
i = 2;
cout << f(b) << endl;
cout << h(i) << endl;
int i1, i2;
// int i3, int i4; // compile error
int i3; int i4; // OK
// short sh, long l; // compile error
short sh; long l; // OK
return 0;
}
/*
g++ Declare.cpp -o Declare
./Declare
Declare
2
3
*/
Notes:
You can write std::cout and std::endl without any using statement. Alternatively, you can use the standard namespace with
using namespace std;
or use only what you need from the standard namespace, as in:
using std::cout;
using std::endl;
In both cases, you can then write cout and endl instead of std::cout and std::endl respectively.
If you use the entire standard namespace, then all the names in std become available, increasing the risk of name collision.
You can run the program with
./Declare
or
Declare
"." is the current directory. Both
program
and
./program
run the program "program"
from the current directory.
You can compile the program without the -o (output) option,
g++ Declare.cpp
creating the file a.out, which you can run with
a.out
./a.out
Chapter_2 | BACK_TO_TOP | Hello Exercise_2-1 |
Comments
Post a Comment