0% found this document useful (0 votes)
28 views6 pages

C++ Programming Basics and Syntax Guide

The document provides a comprehensive overview of C++ programming, covering key concepts such as program structure, identifiers, user-defined data types, variable initialization, control structures, and memory management. It also includes details on data types, operators, character strings, console input/output, functions, and namespaces. Additionally, it discusses file I/O and stream pointers, making it a valuable resource for understanding C++ programming fundamentals.

Uploaded by

joy112833
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views6 pages

C++ Programming Basics and Syntax Guide

The document provides a comprehensive overview of C++ programming, covering key concepts such as program structure, identifiers, user-defined data types, variable initialization, control structures, and memory management. It also includes details on data types, operators, character strings, console input/output, functions, and namespaces. Additionally, it discusses file I/O and stream pointers, making it a valuable resource for understanding C++ programming fundamentals.

Uploaded by

joy112833
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Key C++ Program Structure

// my first program in C++


: #include <diostream.h>
switch —keyword, reserved e
"Hello!" — string {
// comment —commented code cout << "Hello World!":
close () —library function return O;
main — variable, identifier }
variable—pl'aceholderin syntax 77 REgIe 1lae cobhonc
if (exression) - syntax R
statement; cofiment */

Identifiers
These are ANSI C++ reserved words and cannot be used as variable names.

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue,
defaulicadel e tesidomdotibleSFd ynamid CRCaS R | SeMEEn
G e X P 1H CHtNC cc Nt al SEN ' ab
fors friend igoton Hif@ dnline, Hnt M onghi¥mutabl'e SMnamespace; ¥new f'operator W privace;
protected MpublE CEEre S TE TN terpre tROaS T e Gt NEChoTRS ToncedS S0MRS ta t1ch
StaticEcastastructs switchistemplates ithd SERthrow St rue Sty typedei typedd),
typename, union, unsigned. using, virtual. void. volatile. wchar_t

User Defined DataTypes Initialization of Variables


typedef existingtype newtypename; type id: E Ve WY a-toi
Lals
typedef unsigned int WORD; type id,id,id; // multiple declaration
enum name{vall, val2, ...} obj_name: type *id; // pointer declaration
enum days_t {MON,WED,FRI} days: type id = value; // declare with assign
union model_name { type *id = value; // pointer with assign
typel elementl; id = value; // assignment
typez element2i = . . Examples
} object_name; // single character in single quotes
union mytypes_t { S ee
char c; // string in double quotes., ptr to string
int 1 char *str = "Hello";
} mytypes; TN 028
struct packed { // bit fields float e =NAROE IO/ /420
unsigned int flagA:1; // flagA is 1 bic int ary[2] = {1,2} // array of ints
unsigned int flagB:3; // flagB is 3 bic const int a = 45; // constant declaration
3 struct products { // declaration
char name [30];
float price;
Preprocessor Directives Sk
#define ID value // replaces ID with e el appl?; // elasihis Sishuctales
//valiie ¥ror¥eachifocourrence s indchescode GIUgLE
. SRS = illesalas L A0 akhstpuans
#undef ID // reverse of #define Slgiie. nekes = 0 G
#ifdef ID //executes code if ID defined DREs et *pAppl?; // pointer"to Az ptishe
#ifndef ID // opposite of #ifdef LGBl Al = Tty Sobken
#if expr // executes if expr is true g Apekes = O 8 A/ chbe sz
#else // else
#eldf // else if
#endif // ends if block Exceptions
#line number "filename” try {
// #line controls what line number and // code to be tried... if statements
// filename appear when a compiler error statements; // fail, exception is sot
// S oocurs throw exception:
#error msg //reports msg on cmpl. error )
#include “file” // inserts file into code siadaelin {nyge @xegucon) i
// during compilation // code 1n'case of exception
#pragma //passes parameters to compiler )SCBtements'
Data Types Operators
priority/operator/desc/ASSOCIATIVITY
Variable Declaration
special class size sign type nameo.
I =copecRPE R
special: volatile
2 () parenthesis LEFT
class: register, static, extern., auto
[ ] brackets LEFT
size: long, short, double
-> pointer reference LEFT
sign: signed, unsigned
structure member access LEFT
type: int, float, char (required)
sizeof returns memory size LEFT
name: the variable name (required)
++ increment RIGHT
// example of variable declaration
— decrement RIGHT
extern short unsigned char AFlag:
~ complement to one (bitwise) RIGHT
TYPE SIZE RANGE
! unary NOT RIGHT
char 1 signed -128 to 127
& reference (pointers) RIGHT
unsigned O to 255
* dereference RIGHT
short 2 signed -32,768 to 32,767
(type) type casting RIGHT
unsigned 0 to 65,535 +
- unary less sign RIGHT
long 4 signed -2,147,483,648 to =
multiply LEFT
2,147,483,647
/ divide LEFT
unsigned O - 4,294,967 ,295
% modulus LEFT
int varies depending on system +
addition LEFT
float 4 3.4E +/- 38 (7 digits)
- subtraction LEFT
double 8 1.7E +/- 308 (15 digits)
<< bitwise shift left LEFT
long double
>> bitwise shift right LEFT
10 1.2E +/- 4,932 (19 digits)
< less than LEFT
bool 1 true or false
<= less than or equal LEFT
wchar_t 2 wide characters
> greater than LEFT
Pointers
>= greater than or equal LEFT
type *variable; // pointer to variable
== equal LEFT
type *func(); // function returns pointer
!= not equal LEFT
void * // generic pointer type
& bitwise AND LEFT
NULL; // null pointer
A bitwise NOT LEFT
*ptr; // object pointed to by pointer
| bitwise OR LEFT
&obj // address of object
&& logical AND LEFT
Arrays
|| logical OR LEFT
int arry[n]; // array of size n
? : conditional RIGHT
int arry2d[n][m]; // 2d n x m array
= assignment
int arry3d[1][jl[k]: // 3d 1xj xk array
+= add/assign
Structures subtract/assign
struct name {
*= multiply/assign
typel elementl;
/= divide/assign
type2 elementZ2;
%= modulus/assign
>>= bitwise shift right/assign
} object _name; // instance of name
<<= bitwise shift left/assign
name variable; // variable of type namo
&= bitwise AND/assign
[Link]; // ref. of element
A= bitwise NOT/assign
variable->elementl; // reference of
|= bitwise OR/assign
pointed to structure
13 , comma

Character Strings
The string "Hello" is actually composed of 6
characters and is stored in memory as follows:
ANSI C++ Library Files
Char H e 1 1 o \O The following files are part of the ANSI C++
Index 0 1 2 3 4 5 standard and should work in most compilers.
\O (backslash zero) is the null terminator character <alllooEtchnMh>E<hiiESciElh>W<dcqlicHli>
and determines the end of the string. A string is an <exception.h> <fstream.h> <functional.h>
array of characters. Arrays in C and C++ start at <iomanip.h> <ios.h> <diosfwd.h>
zero. <iostream.h> <istream.h> <iterator.h>
Sie = “aleilierd <limits.h> <list.h> <locale.h> <map.h>
str[2] = 'e’'; // string is now ‘Heelo’
<memory.h> <new.h> <numeric.h>
common <sftring.h> functions: <ostream.h> <queue.h> <set.h> <sstream.h>
strcat(s7,s2) strchr(s7,c) strcmp(s7,s2) <stack.h> <stdexcept.h> <streambuf.h>
strepy(s2,s7) strlen(s7) strncpy(s2,s7,n) <strdngfhi>S<typeinfofh> <ttty
Th>
strstr(s7,s2) <valarray.h> <vector.h>
Control Structures Console Input/Output
Decision (if-else) [See File I/0 on reverse for more about streams]
Be (@enelliclen) 4 C Style Console 1/0
statements; stdin — standard input stream
} stdout — standard output stream
else if (condition) ({ stderr — standard error stream
statements; // print to screen with formatting
} pranth(@fcriacilz s a2k
else { printt (TnOmsST %0 ki kc:SIS EEEC
&
statements; //_print to/string s
B Cioelnme(S, weigizie , @l @EEE,
.. .) !
if (x == 3) // curly braces not needed sprintf (SETRTSITSNST Tha W kIR0
)&
flag = 1; // when if statement is // read data from keyboard into
else // followed by only one // namel name2, ...
flag = 0; // statement scanf ("format" , &namel , &name2, ...)
Repetition (while) scanf ("%d ,%f” ,varl ,var2) ; // read nums
while (expression) { // loop until //greaditroniisStringyis
statements; // expression 1is false sscanf (“format" , &namel , &name2, ...)
K SScant (S ki xc At IBvar2)s
Repetition (do-while) C Style 1/0 Formatting
do { // perform the statements %d, %1 dinteger
statements; // as long as condition %c single character
} while (conddtdion). // is true double (float)
Repetition (for) octal
init - initial value for loop control variable pointer
condition - stay in the loop as long as condition unsigned
is true char string
increment - change the loop control variable exponential
fbr(init; @royitelil it @i increment) { hexadecimal
statements; number of chars written
} %g, %G same as f for e,E
Bifurcation (break, continue, goto, exit) C++ console 1/0
break; // ends a loop cout<< console out, printing to screen
continue; // stops executing statements cin>> console in, reading from keyboard
// in current iteration of loop cont- cerr<< console error
// inues executing on next iteration clog<< console log
label: cout<<"Pleaserenter an dnteger:
goto label; // execution continues ac clin=—
1%
// label cout<<'numl: "<<i<<"\n"<<endl;
exit(retcode); // exits program Control Characters
Selection (switch) \b backspace \f form feed \r return
switch (variable) { \' apostrophe \n newline \t tab
case constantl: // chars. ints \nnn character #nnn (octal) \" quote
statements; \NN character #NN (hexadecimal)
break; // needed to end flow
case constantZ:
statements; // allocate memory (C or C++)
break; void * malloc (nbytes); // nbytes=sizo
default: char *buffer; // declare a buffer
statements; // default statemencs // allocate 10 bytes to the buffer
buffer = (char *)malloc(10);
// allocate memory (C or C++)
// nelements = number elements

Dynamic Memory // size = size of each element


void * malloc (nelements, size).
Memory can be allocated and deallocated int *nums; // declare a buffer
// allocate memory (C++ only) // allocate 5 sets of ints
pointer = new type []: nums = (char *)calloc(5,sizeof (int)) :
iWmiE “feieir // declare a pointer // reallocate memory (C or C++)
ptr = new int; // create a new instance void * realloc (*ptr, size):
ptr = new int [5]; // new array of ints // delete memory (C or C++)
// deallocate memory (C++ only) void free (*ptr):
delete [] pointer;
delete ptr; // delete a single int
delete [] ptr // delete array
Overloading Functions
Functions can have the same name, and same
Functions number of parameters as long as the parameters of
In C, functions must be prototyped before the main are different types
function, and defined after the function. In
C++, functions may, but do not need to be, diQide‘(ub' a, b)
prototyped. C++ functions must be defined before
{ (asb); 3}
the location where they are called from.
7l divide ( o a, b)
type name(argl, arg2, ...) {
{ ret (7D )
statementl; divide(10,2);
statement?Z,
divide (10,3)
Recursion
} Functions can call themselves
type - return type of the function factorial ( o n) {
name - name by which the function is called G > 1)
argl, arg2 - parameters to the function : (M *factordals(m=1))"
statement - statements inside the function
(DE
}
: 2@kl (Glae &, e [B) o Prototyping
g P Functions can be prototyped so they can be used
© = g o) after being declared in any order
ey
}
<iostream.
h>
num = add(l 2)
odd (- a);
Passing Parameters even ( a);
Pass by Value main ) { ... )}
function (i var);
Variable is passed into the functlon and can be
changed, but changes are not passed back.
Pass by Constant Value
functdon (¢ g 5k var)
; Namespaces
Variable is passed into the function but cannot be Namespaces allow global identifiers under a name
changed.
Pass by Reference > identifier {
function(int &var); namespace-body;
Variable is passed into the function and can be }
changed, changes are passed back. 1dAllCSPDd

Pass by Constant Reference mlrsie 4 VarnF=8501


function ( &var) = second { ke ware = & I1Z0IEE
Variable cannot be changed in the function. - main () {
Passing an Array by Reference cout << first::var << endl;
It's a waste of memory to pass arrays and cout << second::var << endl;
structures by value, instead pass by reference. OF
int array[1]; = I o) }
ret = aryfunc(&array); > allows for the current nesting
Sy
hitin oG ERatera
v RN DR level to use the appropriate namespace
array[0] = 2; identifier;
. 2 ;

i
Default Parameter Values second { e var
. aelel (e &, dnE B=2) 1 main () {
T second;
r=a+b: cout << var << endl;
(@) collitm=<M(Var2)<=<Nendis
OF
File 1/0 Stream Pointers
[Link]() returns pointer to current location
#include <fstream.h> // read/write file
when reading a file
#include <ofstream.h> // write file
[Link]() returns pointer to current location
#include <ifstream.h> // read file
when writing a file
File I/O is done from the fstream, ofstream, and
// seek a position in reading a file
ifstream classes.
[Link](position);
[Link](offset, direction);
File Handles
// seek a position in writing a file
A file must have a file handle (pointer to the file) to
[Link] (position) ;
access the file.
[Link] (offset, direction);
ifstream infile; // create handle called
direction can be one of the following
// infile to read from a file
ios: :beg beginning of the stream
ofstream outfile; // handle for writing
ios: :cur current position of the stream pointer
fstream f; // handle for read/write
ios: :end end of the stream
Opening Files
Binary Files
After declaring a file handle, the following syntax
buffer is a location to store the characters.
can be used to open the file
numbytes is the number of bytes to written or read.
void open(const char *fname, ios::mode);
write (char *buffer, numbytes);
fname should be a string, specifying an absolute
read (char *buffer, numbytes);
or relative path, including filename. ios: : mode
can be any number of the following and repeat:
in Open file for reading Output Formatting
streamclass £; // declare file handle
out Open file for writing
ate Initial position: end of file // set output flags
[Link](ios_base:
:flag)
app Every output is appended at the end of file
trunc If the file already existed it is erased possible flags
binary Binary mode dec fixed hex oct
ifstream f; // open input file example scientific internal left right
fifopen( InpucHtXe " os i &Hn)" uppercase boolalpha showbase showpoint
OfiSBREAMEEIN/ O PENN T O T RWI | CIToE NED Ity showpos skipws unitbuf
[Link]("[Link]"”, dos::out | ios::binary adjustfield left | right | internal
| 1os::app); basefield dec | oct | hex
floatfield scientific | fixed
Closing a File £.£i11 () get fill character
£.fill (ch) set fill character ch
A file can be closed by calling the handle's close
function [Link](numdigits) sets the precision for
[Link](); floating point numbers to numdigits
[Link](c) put a single char into output stream
[Link] (flag) sets a flag
Reading From a File (Text Mode)
[Link] (flag, mask) sets a flag w/value
The operator >> can be used to read from a file. It
[Link] () returns the current number of
works similar to cin. Fields are seperated in the file
characters to be written
by spaces.
[Link] (num) sets the number of chars to be
ifstream f; // create file handle
written
[Link]("[Link]”); // open file
while ([Link]()) // end of file test
£8>>05>h>> Ol /e ad N To T as bR o
Operators Precedence
I/0 State Flags
Flags are set if errors or other conditions occur. !+, — (unary operators) first ROl
The following functions are members of the file
object second L tOR
[Link] () returns true if a failure occurs in
reading or writing thid [ tO R
[Link] () returns true for same cases as
fouth L tOR
bad() plus if formatting errors occur
[Link]
() returns true if the end of the file
fith LTtOR
reached when reading
[Link] () returns false if any of the above ssch LtOR
were frue
seventh L tO R
(assignment operator) last RtolL
dec oct|hex|ch dec oct hex|ch dec oct hex ch |dec oct hex ch
0 |0 |60 NUL (null) 32 140 |20 |(space)| 64 |100(40 @ ‘96 140/60 |°
1 |1 |01 |SOH (start of header) 33 |41 |21 |! 65 (10141 |A ]97 14161 |a
2 |2 |02 |STX (start of text) 34 (42 |22 |" 66 10242 (B “98 142|162 b
3 [3 |03 [ETX (end of text) 35 |43 |23 |# 67 10343 |C | 99 14363 |c
4 |4 |04 EOT (end of transmission) 36 44 24 |$ 68 10444 |D ||100|144/64 |d
5 |5 |05 ENQ (enquiry) 37 |45 |25 |% 69 |105|45 (E ||101|/145/65 |e
6 |6 |06 ACK (acknowledge) 38 46 |26 |& 70 (106(46 |F ||102|146/66 f
7 |7 |07 |BEL (bell) 39 (47 |27 | 71 (10747 |G ||103|147|67 |g
8 |10 |08 |BS (backspace) 40 |50 |28 |[( 72 |110(48 H ||104|150(/68 h
9 |11 |09 |HT (horizontal tab) 419 5181298 ) 73 |111|49 |I ||165/151|69 |i
10 |12 |Oa |LF (line feed - new line) 42 |52 |2a |* 74 (112/4a |J ||106|152|6a |j
11 |13 Ob |VT (vertical tab) 43 |53 |2b |+ 75 (113/4b |K |[107|153|6b |k
12 |14 |0c FF (form feed - new page) 44 |54 2¢ |, 76 |114|4c |L ||108|154|6¢c |1
13 |15 |0d |CR (carriage return) 45 |55 |2d |- 77 |115/4d M ||109 155/6d |m
14 |16 0Oe |[SO (shift out) 46 |56 |2e |. 78 |116|4e ”N7 116|/156/6e |n
15 |17 |0f |SI (shiftin) 4] |57 |2f |/ 79 (117(4f |0 ||111|157|6F |o
16 |20 10 |DLE (data link escape) 48 60 |30 |6 80 |120|50 |P ||112|160|70 |p
17 |21 |11 DC1 (device control 1) 49 61 31 |1 81 (12151 |Q |[{113|161|71 |q
18 (22 |12 |DC2 (device control 2) 50 (62 |32 |2 82 [122|52 |R ||114|162|72 |r
19 |23 13 |DC3 (device control 3) 518 6301831 3 881(123531(1S [|115(163|738 [s
20 (24 |14 |DC4 (device control 4) ~ |[52 |64 [34 |4 84 12454 |T ||116|164|74 |t
21 |25 |15 |NAK (negative acknowledge) 538 658358 5 85 [125(55 |U |[117|165|75 |u
22 |26 |16 |SYN (synchronous idle) 54 66 |36 |6 86 |126|56 |V |[118/166|76 |v
23 |27 |17 |ETB (end of transmission block)||55 |67 (37 |7 87 [127|57 |W ||119|167|77 |w
24 |30 |18 |CAN (cancel) 56 (70 |38 |8 |88 [130/58 |X ||/120]170/78 |x
25 |31 |19 |EM (end of medium) 578 7183989 89 [131|59 |Y ||121|171|79 |y
26 |32 |la |SUB (substitute) 58 |72 |3a 90 |132|5a |Z ||122|172|7a |z
27 |33 |1b |ESC (escape) 59873 8li3bl ; 91 |133|5b [7 11231173 7b {
28 (34 |1c |FS (file separator) 60 |74 |3c |< 92 |134|5¢c |\ [|124|174|7c |
29 |35 |1d |GS (group separator) 61 |75 |3d |= 93 |135|5d |1 |[125|175(7d |}
30 (36 |le |RS (record separator) 62 |76 |3e |> 94 |136|5e |~ ||126|176|7e |~
31 (37 |1f |US (unit separator) 638 77831 RT 95 |137|5f |_ [|127|177|7f |DEL (delete)

Type Size*® Range (commonly) Format Specifier

short int 2 bytes -3.28x10* to 3.28x10* %hd

unsigned int 2 or 4 bytes 010 6.55x10* (2 bytes) %U


0 to 4.29x10° (4 bytes)

long int 4 or 8 bytes -2.15x10° to 2.15x10° (4 bytes) %ld


-9.22x10" to 9.22x10'® (8 bytes)

long long int 8 bytes -9.22x10"® t0 9.22x10"® %lld

unsigned long int 4 or 8 bytes 0 to 4.29x10° (4 bytes) %Ilu


0 to 1.84x10" (8 bytes)

unsigned long long int 8 bytes 0 to 1.84x10" %llu

long double 8, 12, or 16 bytes Implementation-dependent, higher %Lf


precision than double

You might also like