Copyright 2000-2019 Networking Laboratory
C/C++ programming overview
Sungkyunkwan University
Hyunseung Choo
Computer Networks
Contents Functions
Invocations Function
Function Definitions Return
statements
Function Prototypes
Call by value and call by
reference
Networking Laboratory 2/84
C basics
“Hello World" Program
Data Types & Variables
printf()
Arithmetic & Logical Operations
Conditionals
Loops
Arrays & Strings
Pointer and Array
Programming Tips
File I/O in C++
General File I/O Steps
C++ streams
File I/O Example
More Input/Output File-
Related Functions
Computer Networks
Hello World Program
The source code
#include <stdio.h>
int main()
{
printf("Hello World\n");
return(0);
}
Computer Networks
Hello World Program
How to compile?
$ gcc hello.c –o hello
gcc compiling command
hello.c source file
hello compiler-generated executable file
Note: the default output filename is “a.out”
Computer Networks
How to execute?
./hello
“./ ” indicates the following file “hello” resides under the
current directory.
Hello World Program
Computer Networks
Name Description Size* Range*
char Character or small
integer
1 byte signed: -128 to 127
unsigned: 0 to 255
short int
(short)
Short integer 2 bytes signed: -32768 to 32767
unsigned: 0 to 65535
int Integer 2 or
4 bytes
signed: -32768 to 32767
unsigned: 0 to 65535 Or
signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
long int
(long)
Long integer 4 bytes signed: -2147483648 to 2147483647
unsigned: 0 to 4294967295
float Floating point number 4 bytes 3.4e +/- 38 (7 digits)
double Double precision
floating point number
8 bytes 1.7e +/- 308 (15 digits)
Data types
Computer Networks
int length = 100;
char num = ‘9’; //The actual value is 57
float deposit = 240.5;
unsigned short ID = 0x5544;
Try the following statements, and see what happens:
unsigned char value = -1;
printf(“The value is %d \n”, value);
unsigned char value = 300;
printf(“The value is %d \n”, value);
Variable Declaration
Computer Networks
Result
Definition Memory layout Display comment
unsigned char
value = -1
11111111 255
unsigned char
value = 300
00101100 44 overflow
Computer Networks
Local variable
Local variables are declared within the body of a function, and can
only be used within that function.
Static variable
Another class of local variable is the static type. It is specified by
the keyword static in the variable declaration.
The most striking difference from a non-static local variable is, a
static variable is not destroyed on exit from the function.
Global variable
A global variable declaration looks normal, but is located outside
any of the program's functions. So it is accessible to all functions.
Variable types
Computer Networks
int global = 10; //global variable
int func (int x)
{
static int stat_var; //static local variable
int temp; //(normal) local variable
int name[50]; //(normal) local variable
……
}
An example
Computer Networks
Variable Definition vs Declaration
Definition Tell the compiler about the variable: its type and
name, as well as allocated a memory cell for the
variable
Declaration Describe information “about” the variable,
doesn’t allocate memory cell for the variable
DEFINITION = DECLARATION + SPACE RESERVATION
struct _tagExample { int a; int b; }; struct _tagExample example;
Declaration Definition
Computer Networks
printf() function
The printf() function can be instructed to print integers, floats and string properly.
The general syntax is
printf( “format”, variables);
An exampleint stud_id = 5200;
char * name = “Choo”;
printf(“%s ‘s ID is %d \n”, name, stud_id);
Computer Networks
Format Identifiers
%d decimal integers
%x hex integer
%c character
%f float and double number
%s string
%p pointer
How to specify display space for a variable?
printf(“The student id is %5d \n”, stud_id);
The value of stud_id will occupy 5 characters space in
the print-out.
printf() function
Computer Networks
Why “\n”
It introduces a new line on the output screen.
\a alert (bell) character \\ backslash
\b backspace \? question mark
\f formfeed \’ single quote
\n newline \” double quote
\r carriage return \000 octal number
\t horizontal tab \xhh hexadecimal number
\v vertical tab
printf() function
Computer Networks
Arithmetic Operations
Computer Networks
Arithmetic Assignment Operators
Computer Networks
Increment and Decrement Operators
awkward easy easiest
x = x+1; x += 1 x++
x = x-1; x -= 1 x--
Computer Networks
Example
Arithmetic operatorsint i = 10;
int j = 15;
int add = i + j; //25
int diff = j – i; //5
int product = i * j; // 150
int quotient = j / i; // 1
int residual = j % i; // 5
i++; //Increase by 1
i--; //Decrease by 1
Computer Networks
int i = 10;
int j = 15;
float k = 15.0;
j / i = ?
j % i = ?
k / i = ?
k % i = ?
Example
Computer Networks
The Answer
j / i = 1;
j % i = 5;
k / i = 1.5;
k % i It is illegal.
Note: For %, the operands can only be integers.
Example
Computer Networks
Logical Operations
What is “true” and “false” in C
In C, there is no specific data type to represent “true” and “false”. C uses
value “0” to represent “false”, and uses non-zero value to stand for “true”.
Logical Operators
A && B => A and B
A || B => A or B
A == B => Is A equal to B?
A != B => Is A not equal to B?
Computer Networks
A > B => Is A greater than B?
A >= B => Is A greater than or equal to B?
A < B => Is A less than B?
A <= B => Is A less than or equal to B?
Don’t be confused
&& and || have different meanings from & and |.
& and | are bitwise operators.
Logical Operations
Computer Networks
Short circuiting
Short circuiting means that we don't evaluate the second
part of an AND or OR unless we really need to.
Some practices
Please compute the value of the following logical
expressions?
Computer Networks
int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>
if( i != j || k < j) =>
if( j<= k || i > k) =>
if( j == k && m) =>
if(i) =>
if(m || j && i ) =>
Example
Computer Networks
int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) => false
if( i != j || k < j) => true
if( j<= k || i > k) => true
if( j == k && m) => false
if(i) => true
if(m || j && i ) => true
Did you get the correct answers?
Example
Computer Networks
Conditionals
if statement
Three basic formats,
if (expression){
statement …
}
if (expression) {
statement …
}else{
statement …
}
Computer Networks
if (expression) {
statement…
} else if (expression) {
statement…
} else{
statement…
}
Conditionals
Computer Networks
if(score >= 90){
a_cnt ++;
}else if(score >= 80){
b_cnt++;
}else if(score >= 70){
c_cnt++;
}else if (score>= 60){
d_cnt++
}else{
f_cnt++
}
Example
Computer Networks
switch (expression)
{
case item1:
statement;
break;
case item2:
statement;
break;
default:
statement;
break;
}
The switch statement
Computer Networks
Loops
for statement
for (expression1; expression2; expression3){
statement…
}
expression1 initializes;
expression2 is the terminate test;
expression3 is the modifier;
Computer Networks
int x;
for (x=0; x<3; x++)
{
printf("x=%d\n",x);
}
First time: x = 0;
Second time: x = 1;
Third time: x = 2;
Fourth time: x = 3; (don’t execute the body)
Example
Computer Networks
while (expression) {
statement …
}
while loop exits only when the expression is false.
An example
int x = 3;
while (x>0) {
printf("x=%d n",x);
x--;
}
The while statement
Computer Networks
for <==> while
for (expression1; expression
2; expression3){
statement…
}
expression1;
while (expression2)
{
statement…;
expression3;
}
equals
Computer Networks
Arrays & Strings
Arrays
int ids[50];
char name[100];
int table_of_num[30][40];
Accessing an array
ids[0] = 40;
i = ids[1] + j;
table_of_num[3][4] = 100;
Note: In C Array subscripts start at 0 and end one less than the array size. [0 .. n-1]
Computer Networks
Strings are defined as arrays of characters.
The only difference from a character array is, a symbol
“\0” is used to indicate the end of a string.
For example, suppose we have a character array, char
name[8], and we store into it a string “Choo”.
Note: the length of this string 4, but it occupies 5 bytes.
C h o o \0
Strings
Computer Networks
Functions
Networking Laboratory 36/78
Computer Networks
Invocations Function (1/3)
Function
A C program consists of one or more functions
Every c-program must contain one main() Function
In the case of repeated codes, define the function and call the
function whenever necessary to improve the simplicity
Function types:
Library functions : System Predefined-Functions
User-defined functions : Functions created by Programmers
Function Invocation
Function call: used in the form Function_name().
Function end: the control point go back to the place where the function
was called
Networking Laboratory 37/78
Computer Networks
Invocations Function (2/3)
Networking Laboratory 38/78
Computer Networks
Invocations Function (3/3)
Networking Laboratory 39/78
Computer Networks
Function Definitions (1/2)
Before the function is called, the function must be defined
in the following format.
Networking Laboratory 40/78
Computer Networks
Function Definitions (2/2)
Parameter Type List
Specify the order and data types corresponding to the arguments
passed when calling the function.
Specify the data types and the order in which the arguments are
passed in the function call.
Can be used as identifiers in the function body
Return type
Type of return statement must be matched with return type of the function
Default type : integer type
void type : void if there is no return value
Networking Laboratory 41/78
Computer Networks
The Return Value
Networking Laboratory 42/78
Computer Networks
Function Prototypes (1/2)
Function is defined before the main function
선언형식
return-type function_name (parameter type list);
Networking Laboratory 43/78
Computer Networks
Function Prototypes (2/2)
If the type of the passing parameter does not match the
type of the defined argument, it is converted to the type
specified in the function prototype.
Networking Laboratory 44/78
Computer Networks
Function Definition Order
A general sequence of programs written in one file
1. #include, #define statements
2. Enumeration types and typedef
3. struct definition
4. Function Prototypes
5. main() Function
6 Function Definitions
Networking Laboratory 45/78
Computer Networks
Developing Large Program (2/2)
Networking Laboratory 46/78
Computer Networks
Call by Value and Call by Reference
Call-by-Value
When Function Invocation occurs, a memory area is newly created
for the parameter to receive the value of the argument, and the
value of the argument is copied to the new memory area.
Even if you use Function Invocation parameter as an identifier and
change its value in the content of the function, the actual argument
value is not changed by using another memory area
Call-by-Reference
When Function Invocation occurs, it passes the address of the
argument.
The actual argument value is changed when the value is changed
in the function
Networking Laboratory 47/78
Computer Networks
Example of Call by Value
Networking Laboratory 48/78
Computer Networks
Example of Call by Reference
Networking Laboratory 49/78
Computer Networks
Pointers and Arrays
Networking Laboratory 50/78
Computer Networks
Pointers and Arrays
Pointers and arrays are very closely linked in C.
Array elements arranged in consecutive memory locations
Accessing array elements using pointers
int ids[50];
int * p = &ids[0];
p[i] <=> ids[i]
Pointers and Strings
A string can be represented by a char * pointer.
Pointers and Arrays
Computer Networks
Char name[50];
name[0] = ‘C’;
name[1] = ‘h’;
name[2] = ‘o’;
name[3] = ‘o’;
name[4] = ‘\0’;
char * p = &name[0];
printf(“The name is %s \n”, p);
Note: The p represents the string “Choo”, but not the array
name[50].
Pointers and Arrays
Computer Networks
Command-Line Argument
In C you can pass arguments to main() function.
main() prototype
int main(int argc, char * argv[]);
argc indicates the number of arguments
argv is an array of input string pointers.
How to pass your own arguments?
./hello 10
Computer Networks
What value is argc and argv?
Let’s add two printf statement to get the value of argc and argv.
#include <stdio.h>
int main(int argc, char * argv[]);)
{
int i=0;
printf("Hello World\n");
printf(“The argc is %d \n”, argc);
for(i=0; i < argc; i++){
printf(“The %dth element in argv is %s\n”, i, argv[i]);
}
return(0);
}
Command-Line Argument
Computer Networks
The output
The argc is 2
The 0th element in argv is ./hello
The 1th element in argv is 10
The trick is the system always passes the name of the executable file as
the first argument to the main() function.
How to use your argument?
Be careful. Your arguments to main() are always in string format.
Taking the above program for example, the argv[1] is string “10”, not a
number. You must convert it into a number before you can use it.
Command-Line Argument
Computer Networks
Data Structure
A data structure is a collection of one or more variables, possibly of different
types.
An example of student record
struct stud_record{
char name[50];
int id;
int age;
int major;
……
};
Computer Networks
A data structure is also a data type
struct stud_record my_record;
struct stud_record * pointer;
pointer = & my_record;
Accessing a field inside a data structure
my_record.id = 10; “.”
or
pointer->id = 10; “->”
Data Structure
Computer Networks
File I/O in C++
Networking Laboratory 58/78
Computer Networks
Using Input/Output Files
A computer file
is stored on a secondary storage device (e.g., disk);
is permanent;
can be used to ◼ provide input data to a program ◼ or receive output data from a program◼ or both;
should reside in Project directory for easy access;
must be opened before it is used.
Computer Networks
General File I/O Steps
1. Include the header file fstream in the program.
2. Declare file stream variables.
3. Associate the file stream variables with the input/output sources.
4. Open the file
5. Use the file stream variables with >>, <<, or other input/output functions.
6. Close the file.
Computer Networks
Using Input/Output Files
stream - a sequence of characters
interactive (iostream)
• cin - input stream associated with keyboard.
• cout - output stream associated with display
file (fstream)
• ifstream - defines new input stream (normally associated with a file).
• ofstream - defines new output stream (normally associated with a
file).
Computer Networks
Stream I/O Library Header Files
Note: There is no “.h” on standard header files : <fstream>
iostream -- contains basic information required for all
stream I/O operations
fstream -- contains information for performing file I/O
operations
Computer Networks
C++ streams//Add additional header files you use
#include <fstream>
int main ()
{ /* Declare file stream variables such as
the following */
ifstream fsIn;//input
ofstream fsOut; // output
fstream both //input & output
//Open the files
fsIn.open("prog1.txt"); //open the input file
fsOut.open("prog2.txt"); //open the output file
//Code for data manipulation
.
.
//Close files
fsIn.close();
fsOut.close();
return 0; }
Computer Networks
Object and Member Functions
input_stream.open("numbers.txt“)
Computer Networks
Open()
Opening a file associates a file stream variable declared in
the program with a physical file at the source, such as a
disk.
In the case of an input file:
the file must exist before the open statement executes.
If the file does not exist, the open statement fails and the input stream
enters the fail state
An output file does not have to exist before it is opened;
if the output file does not exist, the computer prepares an empty file
for output.
If the designated output file already exists, by default, the old
contents are erased when the file is opened.
Computer Networks
Validate the file before trying to access
First method Second method
By checking the stream
variable;
If ( ! Mystream)
{
Cout << “Cannot open file.\n ”;
}
By using bool is_open() function.
If ( ! Mystream.is_open())
{
Cout << “File is not open.\n ”;
}
Computer Networks
File I/O Example: Open the file with validation
First Method (use the constructor) Second Method ( use Open function)
#include <fstream>
using namespace std;
int main()
{//declare and automatically open the file
ofstream outFile(“fout.txt");
// Open validation
if(! outFile) {
Cout << “Cannot open file.\n ”;
return 1;
}
return 0;
}
#include <fstream>
using namespace std;
int main()
{//declare output file variable
ofstream outFile;
// open an exist file fout.txt
outFile.open(“fout.txt”);
// Open validation
if(! outFile.is_open() ) {
Cout << “Cannot open file.\n ”;
return 1;
}
return 0;
}
Computer Networks
More Input File-Related Functions
ifstream fsin;
fsin.open(const char[] fname)
connects stream fsin to the external file fname.
fsin.get(char character)
extracts next character from the input stream fsin and places it
in the character variable character.
fsin.eof()
tests for the end-of-file condition.
Computer Networks
File I/O Example: ReadingRead char by char Read a line
#include <iostream>
#include <fstream>
int main()
{//Declare and open a text fileifstream openFile(“data.txt");
char ch;
//do until the end of file
while( ! OpenFile.eof() )
{OpenFile.get(ch); // get one character
cout << ch; // display the character
}
OpenFile.close(); // close the file
return 0;
}
#include <iostream>
#include <fstream>
#include <string>
int main()
{//Declare and open a text file
ifstream openFile("data.txt");
string line;
while(!openFile.eof())
{//fetch line from data.txt and put
it in a string
getline(openFile, line);
cout << line;
}
openFile.close(); // close the file
return 0;
}
Computer Networks
More Output File-Related Functions
ofstream fsOut;
fsOut.open(const char[] fname)
connects stream fsOut to the external file fname.
fsOut.put(char character)
inserts character character to the output stream fsOut.
fsOut.eof()
tests for the end-of-file condition.
Computer Networks
File I/O Example: WritingFirst Method (use the constructor) Second Method ( use Open function)
#include <fstream>
using namespace std;
int main()
{/* declare and automatically open the file*/
ofstream outFile("fout.txt");
//behave just like cout, put the word into the file
outFile << "Hello World!";
outFile.close();
return 0;}
#include <fstream>
using namespace std;
int main()
{// declare output file variableofstream outFile;
// open an exist file fout.txt
outFile.open("fout.txt”);
//behave just like cout, put the word into the file
outFile << "Hello World!";
outFile.close();
return 0;
}
Computer Networks
File Open ModeName Description
ios::in Open file to read
ios::out Open file to write
ios::app All the data you write, is put at the end of the file.
ios::trunc Deletes all previous content in the file. (empties
the file)
ios::nocreate If the file does not exists, opening it with the
open() function gets impossible.
ios::noreplace If the file exists, trying to open it with the open()
function, returns an error.
ios::binary Opens the file in binary mode.
Computer Networks
File Open Mode
#include <fstream>int main(void){ofstream outFile("file1.txt", ios::out);outFile << "That's new!\n";outFile.close();
Return 0;}
If you want to set more than one open mode, just use the OR
operator- |. This way:
ios::app | ios::binary
Computer Networks
Summary of Input File-Related Functions
#include <fstream>
ifstream fsIn;
fsIn.open(const char[] fname)
connects stream fsIn to the external file fname.
fsIn.get(char& c)
extracts next character from the input stream fsIn and places it in the character variable c.
fsIn.eof()
tests for the end-of-file condition.
fsIn.close()
disconnects the stream and associated file.
fsIn >> c; //Behaves just like cin
Computer Networks
Summary of Output File-Related Functions
#include <fstream>
ofstream fsOut;
fsOut.open(const char[] fname)
connects stream fsOut to the external file fname.
fsOut.put(char c)
inserts character c to the output stream fsOut.
fsOut.eof()
tests for the end-of-file condition.
fsOut.close()
disconnects the stream and associated file.
fsOut << c; //Behaves just like cout
Computer Networks
File format
In c++ files we (read from/ write to) them as a stream of
characters
What if I want to write or read numbers ?
Computer Networks
Example writing to file
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
ofstream outFile;
// open an exist file fout.txt
outFile.open("number.txt",ios::app);
if (!outFile.is_open())
{ cout << " problem with opening the file ";}
else
{
outFile <<200 <<endl ;
cout << "done writing" <<endl;
}
outFile.close();
}
Computer Networks
Computer Networks
Example Reading from file #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void main()
{//Declare and open a text file
ifstream INFile("number.txt");
string line;
int total=0;
while(! INFile.eof())
{
getline(INFile, line);
//converting line string to int
stringstream(line) >> total;
cout << line <<endl;
cout <<total +1<<endl;
}
INFile.close(); // close the file
}
Computer Networks
Computer Networks
Programming Tips
Replacing numbers in your code with macros
- don’t use magic numbers directly
#define MAX_NAME_LEN 50;
char name[MAX_NAME_LEN];
Avoiding global variables
- modulation is more important
Giving variables and functions a nice name
- a meaning name
Don’t repeat your code
- make a subroutine/function
Don’t let the function body to exceed one screen
- hard to debug
Computer Networks
Indenting your code (clearance)
if(expression)
{
if(expression)
{
……
}
}
Commenting your code
Don’t rush into coding. Plan first.
Printing out more debugging information
Using debugger (gdb)
Programming Tips
Computer Networks
C vs. C++
C++ is a superset of C
C++ has all the characteristics of C
Using g++ to compile your source code
Recommended IDE: Dev C++ (Newest version)
Computer Networks
Books recommended
The C Programming Language, Brian Kernighan a
nd Dennis Ritchie. Second edition. Prentice-Hall,
1988. (C Bible)
The C++ Programming Language, Bjarne Stroustr
up. Third edition. Addison-Wesley, 1997. (C++ Bib
le)
Advanced Programming in the UNIX Environment,
W. Richard Stevens, Addison-Wesley, 1992. (APU
E)