0% found this document useful (0 votes)
2 views

01.Cpp Basic Syntax.pptx

The document provides an overview of C++ programming, covering its history, basic syntax, data types, and program structure. It discusses the features and philosophy of C++, including its multi-paradigm nature and the importance of user-defined styles. Additionally, it explains variable declaration, initialization, and the use of operators, expressions, and control structures in C++.

Uploaded by

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

01.Cpp Basic Syntax.pptx

The document provides an overview of C++ programming, covering its history, basic syntax, data types, and program structure. It discusses the features and philosophy of C++, including its multi-paradigm nature and the importance of user-defined styles. Additionally, it explains variable declaration, initialization, and the use of operators, expressions, and control structures in C++.

Uploaded by

Soul Century
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

C++ Basic Syntax

THE C++ LANGUAGE, DATA TYPES, EXPRESSIONS,


LOOPS AND FUNCTIONS
Table of Contents
• History, Concepts & Philosophy, Standards
• C++ Program Structure, Compiling & Running C++ Code
• Primitive Data Types in C++
• Declaring & Initializing Variables, Scope
• Operators, Expressions, Conditionals, Loops
• Functions
• Basic Console I/O

2
What is C++
FAST, MID-LEVEL, MULTI-PLATFORM, MULTI-PARADIGM
What is C++?
• General purpose programming language
• Compiles to binary
• Multi-platform, but underlying features may differ between systems
• Statically typed – data in predefined forms (data types)
• Multi-paradigm
• Fast

4
C++ Philosophy
• Features immediately useful in the real world
• Programmers free to pick their own style
• Useful features more important than preventing misuse
• Features you do not use, you do not pay for
• Programmer can specify undefined behavior

• More: en.wikipedia.org/wiki/C++#Philosophy
5
No, not this guy,
sorry

C++ HISTORY
Created 1979 – 1983 by Bjarne…

6
This one. See, Psst! Hey, kids, want
much better! some Classes?

C++ HISTORY
Created 1979 – 1983 by Bjarne…
… Stroustrup
Originally “C with Classes”

7
C++ Standards
• C++ 98 – first standardized C++ version
• Still massively used today
• C++ 03 – minor revision of 98, bug-fixes
• C++ 11 – major revision
• Many new features and improvements
• Initializer lists, Rvalue references, lambdas, range-based loops, etc.
• C++ 14 – latest official revision
• Small features and fixes
• Binary literals, variable templates, more type deduction, etc.
8
C++ Compilers & IDEs
• A C++ compiler turns C++ code to assembly
• i.e. translates C++ to machine language
• An IDE is software assisting programming
• Has a Compiler, Linker, Debugger, Code Editor
• Code organization, Tools, Diagnostics
• There are lots of C++ compilers and IDEs
• Free, open-source, proprietary

9
Code::Blocks
• Free C & C++ IDE
• Comes with MinGW GCC compiler
• C++11 support needs to be enabled from settings
• C++14 support needs more complicated setting to enable
• Lightweight
• Can compile single .cpp file
• Can be used for bigger projects with many files, references, etc.
• We will start the with Code::Blocks and show other IDEs later

10
C++ Program Structure, Compiling & Running C++
ENTRY POINT, COMPILERS & IDES
Hello
Include theWorld
input-
Say we’re working with std
namespace (so we don’t write
output library std:: in front of everything)
• Here’s a classic C++ “Hello World” example
1 #include <iostream> Parameters in
2 using namespace std;
3
these brackets are
4 int main(int argc, char * argv[]) { optional
5 cout << "Hello World!" << endl;
6 return 0;
7 }

Print to
the console
"main" function –
our entry point For main, 0 means everything
went ok, terminating normally
12
C++ Entry Point & Termination
• The main function – entry point of the program
• No other function can be named "main"
• C++ needs specific function to start from
• Everything else is free-form – code ordering, namings, etc.
• Can receive command line parameters
• Termination – main finishes (returns), the program stops
• The return value of main is the "exit code“
• 0 means no errors – informative, not obligatory

13
Program Structure: Including Libraries
• C++ has a lot of functionality in its standard code libraries
• C++ can also use functionality from user-built code libraries
• Say what libraries to use with the #include syntax
• For now, for standard libraries: put the library name in <>
1 #include <iostream>
2 using namespace std;
3 iostream contains console I/O
4 int main(int argc, char * argv[]) {
functionality

14
Program Structure: Blocks
• Basic building block (pun intended) of a program
• Most actual program code is in blocks, aka “bodies”
• Start with { and end with }, can be nested
• Functions’ (like main()), loops’ & conditionals’ code is in blocks
4 int main(int argc, char * argv[])
5 { main() code block
5 cout << "Hello World!" << endl;
6 return 0;
7 }

15
Program Structure: Statements & Comments
• Statement: a piece of code to be executed
• Blocks consist of statements
• Statements contain C++ code and end with a ;
4 int main(int argc, char * argv[]) A statement
5 {
5 cout << "Hello World!" << endl;
6 return 0; Another statement
7 }
(Note: usually 1 per line)
• C++ has comments (parts of the code ignored by compiler)
• // comments out an entire line, /* starts a multi-line comment, */ ends it

16
C++ Hello World
LIVE DEMO
Variables & Primitive Types
INTEGERS, FLOATING-POINT, CHARACTERS,
VARIABLE DECLARATION, INITIALIZATION, SCOPE
Fast Intro: Declaring and Initializing Variables
• <data_type> <identifier> [=
<initialization>]; int numGlobal;

• Declaring: int num; int main() {


int num;
• Initializing: num = 5; num = 5;
int sameNum(5);
return 0;
• Combined: int num = 5, }
and additionally int num(5);
• Can declare multiple of same type by separating with comma (,)
• int trappist1BMassPct=85, trappist1CMassPct=80; is valid
• NOTE: int num() is not a default initialization – it’s a function declaration.

19
Declaring & Initializing Variables
LIVE DEMO
TIME:
TIME’S UP!

Quick Quiz:
• Tony gives George 5 apples
• Later, Angus gives George 3 apples
• How many apples does George have?

21
C++ PITFALL:
UNINITIALIZED LOCALS
George has 13837 apples.
Why?
Nobody said George had 0 apples to
begin with.

22
Uninitialized Locals
LIVE DEMO
Local & Global Variables
• Global: defined outside blocks, usable from all code
• Local: defined inside blocks, usable only from code in their block
• Locals DO NOT get initialized automatically
• Globals get initialized to their “default” value (0 for numerics)
int secondsInMinute = 60;
int minutesInHour = 60;
int hoursInDay = 24;
int secondsInHour = secondsInMinute * minutesInHour;
int main() {
int days = 3;
int totalSeconds = days * hoursInDay * secondsInHour;

24
Global & Local Variables
LIVE DEMO
const Variables
• C++ supports constants – “variables” that can’t change value
• Can and MUST receive a value at initialization, nowhere else
• Can be local, can be global
• secondsInMinute, minutesInHour, etc., aren’t things that
normally change in the real world – the following won’t compile:
const int secondsInMinute = 60;
int main() {
secondsInMinute = 13; //compilation error

• NOTE: the const keyword has other uses which we’ll discuss later on

26
const Variables
LIVE DEMO

Yes, I know that’s not how


that meme’s used. Shut up.
Other variable modifiers
• static variables initialize once and exist throughout program
• Can be used to make a local variable that acts like a global one
• Can be global, but that’s basically the same as a normal global variable
• We’ll talk more about them later
• extern tells the compiler a variable exists somewhere in a multi-
file project
• Will discuss this in another lecture
• register is a hint to compiler where to store the variable
• Mostly redundant these days

28
Primitive Data Types
R E P R E S E N T I N G I N T E G E R , F LO AT I N G - P O I N T
A N D S Y M B O L I C VA LU E S
Integer Types – int
• C++ has “only one” integer type – int
• “Width” modifiers control the type’s size and sign
• short – at least 16 bits; long – at least 32 bits
• long long – 64 bits (C++11, Windows supports it on C++03 too)
• signed and unsigned control whether memory used for sign data
• Modifiers can be written in any order
• int can be omitted if any modifier is present
• Defaults: int “usually” means signed long int

30
Integer Sizes and Ranges
• The C++ standard doesn’t have very strict size guarantees
• Depends on implementation, but int is 32-bits on most mainstream PCs
• Use the sizeof(int) operator to get the size (in bytes) on your system
• Ranges depend on size, a 32-bit integer has about 4 billion values
• So, a signed 32-bit integer has the range of about (-2 billion, +2 billion)
• Average human lifespan is about 2 billion seconds. int is older than you!
• Sizes: http://en.cppreference.com/w/cpp/language/types#Properties
• Ranges: http://en.cppreference.com/w/cpp/language/types#Range_of_values

31
Integer Types
LIVE DEMO
Floating-Point Types
• Represent real numbers (approximations)
• 2.3, 0.7, -Infinity, -1452342.2313, NaN, etc.
• float: single-precision floating point, usually IEEE-754 32-bit
• double: double-precision floating point, usually IEEE-754 64-bit
Name Description Size* Range*
float Floating point number. 4bytes ±1.5 × 10−45 to ±3.4 × 1038 (~7 digits)

double Double precision floating point 8bytes ±5.0 × 10−324 to ±1.7 × 10308 (~15 digits)
number.

Long double precision floating


long double point number. 8bytes ±5.0 × 10−324 to ±1.7 × 10308 (~15 digits)

33
Using Floating-Point Types
LIVE DEMO
Guaranteeing Type Sizes
• C++ has some tentative cross-platform support for fixed-size types
• There is the C++11 bitset, the cstdint library, etc.
• Code running on most systems has access to system macros
• E.g. on Windows: INT32, INT8, FLOAT, INT_PTR, LONG_PTR
• If you know the system, you can use those macros to guarantee size
• Universally-portable code with fixed type sizes is not really possible
• Do you really expect a toaster to guarantee a 64-bit integer?
• In most cases, type-size guarantees are not necessary

35
char
NO, NOT THIS CHAR THE C++ CHARACTER TYPE

36
Character Types – char
• char is the basic character type in C++
• Basically an integer interpreted as a symbol from ASCII
• Guaranteed to be 1 byte – a range of 256 values
• Initialized by either a character literal or a number (ASCII code)
int main() {
char letter = 'a';
char sameLetter = 97;
char sameLetterAgain = 'b' - 1;
cout << letter << sameLetter << sameLetterAgain << endl;
return 0;
}

37
Using char as a Number
• char is essentially a 1-byte integer, it can be used as such
• char is also useful when processing data byte-by-byte
• Always use signed or unsigned when using char as a number
• Guarantees the range of char as [-128, 127] or [0, 255]
respectively
• Otherwise the system picks whatever it thinks is best for character
representation
• … you don’t want the system pretending to be smart
• Avoid using char as a number unless you have a good reason to

38
Using Character Types
LIVE DEMO
Boolean Type – bool
• bool – a value which is either true or false, takes up 1 byte
• Takes true, false, or numeric values
• Any non-zero numeric value is interpreted as true
• Zero is interpreted as false
int main() {
bool initializedWithKeyword = true;
bool initializedWithKeywordCtor(false);
bool initializedWithZero = 0;
bool initializedWithNegativeNumber(-13);

40
Using bool
LIVE DEMO
Rules for C++ Identifiers
• We’ve been declaring variables using some rules
• Variable names are a type of identifier
• Data types, functions, classes, etc. are identifiers
• Allowed symbols: alphabetic characters, digits, underscores
• Can’t begin with a digit
• Case-sensitive
• Can’t be a reserved C++ keyword (like int, return, true, etc.)

42
Implicit & Explicit Casting
• Types which “fit” into others can be assigned to them implicitly
• For integer types, “fit” usually means requiring less bytes
• E.g. char a = ‘a’; int i = a; is a valid operation
• But int i = 97; char a = i; is not
• For floating point, float fits into double
• If you really want to store a “bigger” type in a “smaller” type:
• Explicitly cast the “bigger” type to the “smaller” type:
smallType smallVar = (smallType) bigVar;
• Can lose accuracy if value can’t be represented in “smaller” type

43
Expressions, Operators,
Conditionals, Loops,
LITERALS, IF, SWITCH, ELSE, FOR, WHILE,
C++ Literals
• Represent values in code, match the primitive data types
• Integer literals
• Value in a numeral system – decimal, octal, hex, and binary (C++11)
• Suffix to describe sign and width (like the int modifiers)
• Floating-point literals
• Digit sequence decimal OR exponential notation
• Suffix to describe precision (single or double-precision)

45
C++ Non-Numeric Literals
• Character literals – letters surrounded by apostrophe (‘)
• String literals – a sequence of letters surrounded by quotes (“)
• That’s what we used to print Hello World!
• Boolean literals – true and false

46
C++ Literals – Things to Keep in Mind
• Integers are positive – writing a - does a minus operation
• Integers should be suffixed if they are too large for a simple int
• Compiler might try to extend automatically, but don’t rely on it
• Floating-points are double by default, suffix with f for float
• Note: there are also string literals – discussed in another lecture
#include<iostream>
using namespace std;
int main() {
cout << -42 << " " << 052 << " " << 0x2a << " " << 0x2A << endl
<< 0.42 << " " << .42f << " " << 42e-2 << endl;
}

47
C++ Literals
LIVE DEMO
Expressions and Operators
• C++ operators and expressions are similar to other languages’
• Operators:
• Perform actions on one or more variables/literals
• Can be customized for different behavior based on data type
• C++ operator precedence and associativity table:
http://en.cppreference.com/w/cpp/language/operator_precedence
• Don’t memorize. Use brackets and look up precedence when necessary
• Expressions: literals/variables combined with operators/functions

49
Commonly Used C++ Operators
Category Operators
Arithmetic + - * / % ++ --
Logical && || ^ !
Binary & | ^ ~ << >>
Comparison == != < > <= >=
Assignment = += -= *= /= %= &= |= ^= <<= >>=
String +
concatenation
Other . [] () a?b:c new delete * -> :: (type) << >>

50
C++ Operators & Expressions

LIVE DEMO
Conditionals
• C++ supports if-else and switch-case for code branching
• The if-else statement takes in a Boolean expression
• If the expression evaluates to true, the if block is executed
• If the expression evaluates to false, the else block is executed
• The else block is optional
• Block { } brackets can be omitted if only 1 statement (not recommended)
double value1 = 5 * 5 / 2.f, value2 = 5 * 5 / 2;
if (value1 > value2) {
cout << "value1 is larger" << endl;
} else {
cout << "value2 is larger" << endl;
}

52
“Chaining” if-else
T H E C O D E B E L O W I S E Q U I VA L E N T. E A C H E L S E
CAN “CHAIN” SEVERAL CHECKS B L O C K C O N TA I N S 1 “ I F ” S TAT E M E N T, S O T H E Y
D O N ’ T N E E D B R A C K E T S . T H E L E F T VA R I A N T
ONE AFTER THE OTHER SKIPS THE BRACKETS

if (value1 > value2) { if (value1 > value2) {


cout << "value1 is larger"; cout << "value1 is larger";
} else if (value1 == value2) { } else {
cout << "values are equal";
if (value1 == value2) {
} else {
cout << "value2 is larger"; cout << "values are equal";
} } else {
cout << "value2 is larger";
}
}

53
TIME:
TIME’S UP!

Quick Quiz
• What will this code print out to the console?
#include<iostream>
using namespace std;

int main() {
int a = 5;
int aMod3 = a % 3;

if (a = aMod3) {
cout << "equal" << endl;
} else {
cout << "not equal" << endl;
}

return 0;
}

54
C++ PITFALL:
ASSIGNMENT INSTEAD
OF COMPARISON IN
CONDITIONAL
Check the code again.
The expression in the if is not the
== check, it is the = assignment,
Which here is non-zero, evaluates to
true, so we go in the if block

55
if and if-else
LIVE DEMO
switch-case
• Example of C++ switch-case usage
switch (day)
{
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
case 4: cout << "Thursday"; break;
case 5: cout << "Friday"; break;
case 6: cout << "Saturday"; break;
case 7: cout << "Sunday"; break;
default: cout << "Error!"; break;
}

57
switch-case structure
• The C++ switch statement takes in
• An integer expression OR an enumeration type (we’ll discuss enums later)
• OR something which implicitly converts to an int (like char)
• The case block can contain case labels and any other code
• Each label has an expression of the same type as the switch
• The case block can also contain the break statement
• If reached, code continues from after the case block
• There is a special default label (without an expression)

58
switch-case execution
• The switch evaluates the expression and finds the matching
case
• Matching means the value of the case matches the value of the switch
• Any code before the matching case is skipped
• Any code after the matching case is executed
• Until break or the end of the block is reached
• Note: this means other case labels may be executed after the matching one!
• If there is no matching case
• If the block contains the special default label, it is executed
• Otherwise the case block is skipped
59
switch-case
LIVE DEMO
Loops
• C++ has the 3 common types of loops – for, while and do-while
• Each loop consists of a loop condition and a loop block (body)
• 1-statement blocks don’t need { }
• Basically the same syntax as if-else

• C++ loop control keywords:


• break – interrupts the loop and continues after its block
• continue – the current iteration skips the remaining part of the loop block

• C++11 also added a range-based for loop


• We’ll discuss it in the lecture on arrays & pointers

61
for Loop
• Syntax: for([init]; [condition]; [increment]) {body
code;}
• The init statement can declare and initialize variables
• Declared variables are usable only IN the for’s body, but usually initializes
the loop’s control variable
• The loop runs while the condition statement evaluates to true
• The increment statement is executed AFTER the for’s body
• Usually increments the loop’s variable, but can execute any expression
• init and increment expressions are separated by comma (,)
62
Fibonacci with “Empty” for Loop
• Every time you do something like this, a kitty dies
int currentNum = 1;
for(int i = 2, lastNum = 1, newCurrent;

i < fibonacciToCalculate;

i++, newCurrent = lastNum + currentNum,


lastNum = currentNum, currentNum = newCurrent) {
}

cout << currentNum << endl;

63
for Loop
LIVE DEMO
while Loops
• while syntax: while (condition) { body code; }
• Executes body until condition becomes false
• Body may never execute
int age = 0;
while (age < 18) {
cout << "can't drink at age " << age << endl;
age++;
}
cout << "age " << age << ", can finally drink!" << endl;

• do-while syntax: do { body code; } while (condition);


• First executes body, then checks condition
• Guaranteed to execute at least once

65
while Loops
LIVE DEMO
Functions
DEFINING, IMPLEMENTING, CALLING,
OVERLOADING
What is a Function?
• A kind of building block that performs a specific task
• A named block of code, which can be called from other code
• Can take parameters and return a value
• Similar to math functions like cos(α), sin(α), tan(α), etc.
• All of these are actually functions you can use in C++
• Allow programmers to construct large programs from simple pieces
• Also known as methods, procedures, subroutines
• main() is also a function, remember?

68
Calling Functions
• Using functions is almost like using variables, however:
• You don’t assign them values (imagine they are constants)
• You write () after them, which could contain parameters
• void functions just do something – you can’t use their “values”
• Most functions return a value – you can use it in an expression
#include<iostream>
#include<cmath>
using namespace std;
int main() {
double degrees = 60;
double radians = degrees * M_PI / 180.0;
cout << sin(radians) << endl;
cout << cos(radians) << endl;
}
69
Calling Functions
LIVE DEMO
Declaring and Defining Basic Functions with C++
• Declare the function #include<iostream>
int getMax(int a, int b) {
return type, its name int maxValue;
and parameters if (a > b) {
maxValue = a;
} else {
• Define the body maxValue = b;
}
• always in a block
return maxValue;
• contains the actual }
function code
int main() {
• Call them same as you std::cout << getMax(5, 7) << std::endl;
return 0;
call other functions }

71
Declaring & Defining Functions

LIVE DEMO
Function Declaration
• Syntax: returnType functionName(parameters)
• The return type can be any C++ data type, or void
• The function name follows the identifier rules (like variables)
• Parameters: empty, single, or several separated by (,)
• Parameter syntax:
• dataType parameterName [= defaultValue]
• If only declaring, parameter name is also optional

73
Function Declaration vs. Definition
• Can be declared without being defined (given a code block)
• Declaration can happen anywhere and happen multiple times
• Global scope, blocks of code in other functions, etc.
• Declaration visibility follows same rules as variable visibility
• Useful for code organization (we’ll discuss in later lectures)
• A function could be declared but not defined anywhere
• If some code calls it, an error will happen at compilation

74
Parameters and Return Value
• Parameters are just variables living in the function’s block
• Parameters with default values:
• Can be omitted by the caller
• If omitted are initialized with the default value
• Must be last in the parameter list
• return immediately exits the function
• Non-void functions must have a return
• Non-void functions follow up return with a value to give back to the
caller

75
Parameters and Return Value

LIVE DEMO
Overloaded Functions
• Same function name and return type, different parameter list
• Different number or types of parameters
• Indicate same operation can be done on different data
• Overloaded functions often defer to each-other
int getMax(int a, int b) {
if (a > b) {
return a;
}
return b;
}

int getMax(int a, int b, int c) {


return getMax(a, getMax(b, c));
}

77
Parameters and Return Value

LIVE DEMO
static Variables Inside Functions
• Remember the static keyword?
• Variable lives through entire program, even if declared locally
• Initialized only once
• static variables can be used inside functions to track state
• E.g. how many times a function was called
double movingAverage(int nextNumber) {
static int numbers = 0;
static int total = 0;
total += nextNumber;
numbers++;
return total / (double)numbers;
}

79
static Variables Inside Functions

LIVE DEMO
Basic Console I/O
WRITING TO & READING FROM CONSOLE USING
I/O STREAMS
C++ Streams
• Things (classes) that either read or write data piece by piece
• Example: we’ve been using cout throughout this lecture
• Writes data to the console (standard output)
• cout has a counterpart – cin
• Reads data from the console (standard input)
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}

82
Streams – Reading from & Writing to
• Streams overload the << and >> operators
• Left-hand side operand is the stream
• Right-hand side operand is the data
• Notice the direction of << and >>
• stream << variable; - the variable (data) goes into the stream
• stream >> variable; - the stream goes into the variable
• Streams use the data type of the variable:
• << : To decide how to write it
• >> : To know how much to read and how to save it into the variable

83
Chaining << and >> operators
• Stream << and >> are still operators, so they must return a value
• A reference to the stream is obtained each time you use << or >>
• Basically, the result the operation is the stream itself
• So, doing cin >> value gives you cin, on which you use >> again
• That’s why cin >> value >> otherValue works, same for cout

84
Basic Stream Reading and Writing

LIVE DEMO
Reading (Multiple) Numeric Values with cin
• Expects console data to mostly match variable type literals
• Expects input data to be separated by one or more spaces/lines
• For integer types, a sequence of digits is expected
• Can have sign, can NOT have type suffix (like L, ULL, etc.)
• For floating-point types:
• Can be an integer
• Can be a sequence of digits separated by “.”
• Can be exponential notation (e.g. 0.42e+2 will be read as 42)

86
Reading Multiple Numbers
LIVE DEMO
Details on cin
• cin is defined in the <iostream> library
• Console input is sent when you press enter, not while you type
• If cin can’t read the input it goes into a fail state
• Input remains on the stream
• cin used as a Boolean – returns if not in fail state
• cin.getline() can be used to read an entire input line directly
• We will discuss advanced console input in a following lecture

88
Details on cout
• The endl we’ve been using so far with cout:
• Represents the system’s newline symbol(s)
• E.g. for Windows – “\r\n”, for Unix – “\n”
• setprecision: how many digits to use for printing floating-
points
• Start count after or before the dot: depends on if we have fixed or not
• fixed: floating-point digits should be counted after the dot
• You can unset it using cout.unsetf(ios_base::fixed)
• When not set, all digits are counted

89
Summary
• We talked about
• Integer & Other types, Initialization details, Scope, Expressions
• Language capabilities like if-else, switch, loops and their specifics
• Functions and how to declare and define them in C++
• Next time
• Arrays and their variants and usage in C++
• References, Pointers and Basic memory management
• Strings & Streams (advanced I/O)

90
Questions?

91

You might also like