“Hello World”
Here’s the famous first C/C++ program: “Hello World!”
#include <stdio.h>
int main()
{
printf("Hello world!\n");
return 0;
}It prints:
Hello world!
followed by a newline.
NOTE: This is old-style C I/O.
C++ has a better way – more later.
Here’s a slightly more complex program:
#include <stdio.h>
int main()
{
int total = 0;
int i;
for (i = 0; i < 10; i++)
{
total = total + i;
}
printf("Total = %d\n", total);
return 0;
}which adds up all the numbers between 0 and 9 (inclusive), and then outputs the result:
Total = 45
followed by a newline.
#include, main, Function Body, etc.
- #include — a preprocessor directive.
- int main() { … } — a function definition (in this case, the main entry point for the program).
- { … } — the function body; a block.
- int total = 0; — a variable definition, with an initializer.
- for (…) { … } — a for loop, containing a body (block).
- printf(…); — a call to the system-supplied printf function, supplying two arguments: the format string, and a parameter to be inserted into that string.
- return 0; — a return statement, returning a value from the function.
Declarations, Definitions, Statements, Expressions, Literals, & Variables
#include <stdio.h>
int main()
{
int total = 0;
int i;
for (i = 0; i < 10; i++)
{
total = total + i;
}
printf("Total = %d\n", total);
return 0;
}Within the main function body, you can see:
declarations/definitions, such as:
int i;
statements, such as:
for (…) { … }
printf(…);
total = total + i;
return 0;
Statements and declarations/definitions are terminated by a semicolon (except for those ending with blocks).
You can also see expressions:
i = 0
i < 10
i++
0
This program uses:
literals:
0 -- a numeric literal
10 -- another numeric literal
"Total = %d\n" -- a string literal
variables:
total -- a variable of type int (integer)
i -- a variable of type int (integer)
Comments
#include <stdio.h>
/* sum.cpp
A program to sum the numbers 0-9
*/
int main()
{
int total = 0; // Holds result
int i; // Loop index
// Loop from 0-9, inclusive
for (i = 0; i < 10; i++)
{
// Add next value
total = total + i;
}
// Print result
printf("Total = %d\n", total);
// Return success status
return 0;
}
Comments can be:
- /* … */ , potentially over several lines.
- // … , until end of current line.
Data Types
Variables in C/C++ must be declared as having a data type. Here are your choices:
char // an individual character,or a "tiny" integer
short // a small integer
int // an integer
long // a larger integer
long long // an even larger integerfloat // single precision floating point
double // double precision floating point
long double // extended precision floating point
bool // Boolean value (true or false) (C++ only)
wchar_t // wide characterIntegers may be signed (the default) or unsigned (a modifier)
Numeric Literals
Examples of Integer Literals:
20 // decimal
024 // octal (indicated by a leading 0)
0x14 // hexadecimal (indicated by a leading 0x or 0X)
128u // unsigned integer literal
1024Ul // unsigned long literal (that's a lowercase 'l' -- prefer 'L')
-1L // long literal
+8Lu // unsigned long literalExamples of Floating Point Literals:
3.14159 // double precision floating point
3.14159F // single precision floating point (use trailing 'F' or 'f')
3.14159L // extended precision floating point (use trailing 'L' or 'l')
3e1 // double precision floating point, scientific notation
1.0E-3F // single precision floating point, scientific notation
-0.34e+5L // extended precision floating point, scientific notationString and Character Literals
Character literals can consist of a single character, and are enclosed within single quotes (apostrophes: ‘):
'a' ; '5' ; ',' ; '"' ; ' ' (space)
Strings are simply arrays of characters in C; they are not first-class data types.
String literals can consist of zero or more characters, and are enclosed within double quotes:
"Bryan" ; "C++ Programming" ; " - / $ " ; "" (null string)
Wide-character literals are just like regular character or string literals, except that they are preceded by an L:
L'a'; L"Bryan"
Escape Sequences
To represent non-printable and special characters, in string and character literals, we use escape sequences:
'\n' // newline (line feed)
'\t' // horizontal tab
'\v' // vertical tab
'\b' // backspace
'\r' // carriage return
'\f' // form feed
'\a' // alert (bell)
'\\' // backslash
'\?' // question mark
'\'' // single quote (apostrophe)
'\nnn' // character whose octal value is nnn (where 'n' represents an octal digit, 0-7 - up to 3 octal digits)Examples:
'\7' // audible bell
'\n' // newline (line feed)
'\0' // null character
'\062' // ASCII value of character 2
'\t' // horizontal tab
"\\Hello\\, \"World\"!\n"
// \Hello\, "World"! followed by newline
'\'' // single quote character
"Hello, \
Cruel World!\n"
// continue string literal onto next lineBoolean Literals
Variables of type bool can take one of two literal values:
true
false
For example:
bool running = true;
while (running)
{
// …
if (areDone())
{
running = false; // cause loop to exit
}
}
Expressions, Operands, & Operators
An expression consists of one or more operands, and (optionally) an operation to be applied to them:
53 // (a numeric literal is a simple expression)
horsefeathers. // (a variable name is a simple expression)
salary + raise
sale_price * discount
"Fred " + "Bloggs " + " Jr."
Arithmetic Operators
The Arithmetic Operators are:
- expr1 * expr2 — multiplication
- expr1 / expr2 — division
- expr1 % expr2 — remainder (modulus)
- expr1 + expr2 — addition
- expr1 – expr2 — subtraction
Division between integers results in an integer, with any fractional part truncated.
The modulus operator operator may only be applied to two integers (a%b), and returns the remainder from the division a/b. [Note: This is well defined only if both operands are positive.]
Autoincrement & Autodecrement Operators
The AutoIncrement Operators are:
- ++lvalue — pre-increment
- lvalue++ — post-increment
The Autodecrement Operators are:
- —lvalue — pre-decrement
- lvalue— — post-decrement
The operators ++ and −− can be used as both prefix and postfix operators. The value of ++x is the new (that is, incremented) value of x. For example, y=++x is equivalent to y=(x=x+1). The value of x++, however, is the old value of x. For example, y=x++ is equivalent to y=(t=x, x=x+1, t), where t is a variable of the same type as x.
Decrementing is similarly expressed by the −− operator.
The ++ operator is used to express incrementing directly, rather than expressing it indirectly using a combination of an addition and an assignment. Provided lvalue has no side effects, ++lvalue means lvalue+=1, which again means lvalue=lvalue+1. The expression denoting the object to be incremented is evaluated once (only).
Equality & Relational Operators
The Equality Operators are:
- expr1 == expr2 — is equal to (Note the common mistake of typing = ! : (expr1 = expr2) is NOT the same as (expr1 == expr2))
- expr1 != expr2 — is not equal to
The Relational Operators are:
- expr1 < expr2 — is less than
- expr1 > expr2 — is greater than
- expr1 <= expr2 — is less than or equal to
- expr1 >= expr2 — is greater than or equal to
Logical & Bitwise Operators
The Logical Operators are:
- expr1 && expr2 — Logical AND
- expr1 || expr2 — Logical OR
- ! expr — Logical NOT
The Bitwise Operators are:
- expr1 & expr2 — Bitwise AND
- expr1 | expr2 — Bitwise OR
- expr1 ^ expr2 — Bitwise XOR
Simple Statements
An Expression Statement is:
- expr;
or:
- ; (the null statement)
Examples of Expression Statements:
42 ; // expression result/value is discarded
anna + kingOfSiam; // value of expression discarded
; // null statement
x = y * z; // Remember, in C/C++, = is an operator
printf("Hello!"); // any value returned by the function is discarded
Compound (Block) Statements
A Compound Statement (also known as a block) is a sequence of zero or more statements enclosed within curly braces ({…})
For example:
{
int value = readFromUser();
writeOut( process(value) );
}
if Statements
An if statement has the following forms:
if (condition)
statement
or:
if (condition)
statement
else
statement
Note that the parentheses around the condition are required.
Example:
if (x == y)
printf("x and y are equal\n");
switch Statements
A switch statement has the form:
switch (condition)
{
case constant-expression :
statement
. . .
default : // Optional
statement
}
Example:
switch (color)
{
case black:
printf("black");
break;
case green:
printf("green"); break;
default:
printf("no color");
}Loops (Iteration Statements)
Loops come in four forms:
- while statement (pre-tested):
while (condition)
statement
- do statement (post-tested) — error-prone; not usually recommended:
do
statement
while (expression)
- for statement:
for ( init; condition; iterate-expr )
statement
- range-for statement (since C++11):
for (for-declaration : expression)
statement
Examples:
while (is-true)
dosomething();
do
dosomething()
while (until-false);
for (int i = 0; i < 10; i++)
printf("%d ", i);
int a[] = {0, 1, 2, 3, 4, 5};
for (int n : a)
printf("%d ", n);break, continue, & goto
A break statement, inside a loop, causes loop termination.
A continue statement, inside a loop, causes the loop to go to the next iteration.
A goto statement transfers control to the statement identified by the specified label:
goto whereever;
Note: Do not use goto, except when you have absolutely no alternative. Even then, think again!
A return statement returns a value from its enclosing function, to the function’s caller:
return 5 * currentPay;
Functions
Functions come in the following flavors:
- Functions provided by the compiler environment/system
printf, scanf, exec, & lots more…
- Functions provided by some other organization
- Third party software vendors
- Your own organization, or others within the same company
- Others
- Functions written by you
Function Declarations & Headers
Whoever supplies a function is responsible for providing a well-documented interface to it.
In particular, a function should be declared in some module, and that module should have one or more header files defined for it.
When a function is supplied by the compiler environment, the header file is accessed using a precompiler directive of the form:
#include <stdio.h> // The standard I/O header
where the angle brackets are a convention for “system-supplied”
Usually, when a module of functions is supplied by a third party (not the compiler environment/vendor), corresponding header files are of the form:
#include "byglop.h" // Enclosed in double quotes.
This is also the approach you should take with your own modules of functions. Always provide the function interface declarations in a well-defined and well-known header file.
Other Preprocessor Directives
There are a number of other preprocessor directives that may be used:
- Macro definition:
#define PI 3.141259
#define max(v1,v2) ((v1)>(v2))?(v1):(v2)
This is C’s approach to:
- Defining constants
- Optimizing certain functions so that they can be expanded inline for better performance.
Be careful with #define! It is very tricky and error-prone!
C++ has implemented better solutions for most of the preprocessor directives
Here’s another useful set of directives:
- Conditional compilation:
#ifdef MSDOS
// Do whatever one needs to do for MS-DOS support
#endif
There is a very important usage of this, known as a guard. It prevents multiple includes of a header file from messing up a compilation. Here’s an example skeleton header file that uses a guard:
#ifndef FRAG_H
#define FRAG_H // It doesn't matter what it's defined to.
// Header file contents go here
#endif FRAG_H
Conditional compilation is often used to create a debug version of a program.
End of Whirlwind Tour
This was an attempt to give you a very fast “leg-up” on learning the basics of C/C++.
Don’t expect to know everything about these languages at this point! There’s so much more to understand, and we’ll be learning much more through the rest of the course.
Onward!