C Chapter01
C Chapter01
C++
Bjarne Stroustrup (Bell Labs, 1979) started as extension to C (macros and variables) added new useful, features nowadays a language of its own C++ (the next thing after C, though wouldnt ++C be more appropriate?)
Outline
Intro to C++
Object-Oriented Programming Changes in C++
comments variable declaration location initialization pointer changes tagged structure type enum types bool type
Object-Oriented Programming
First-class objects - atomic types in C
int, float, char have:
values sets of operations that can be applied to them
Object-Oriented Idea
Make all objects, whether C-defined or userdefined, first-class objects For C++ structures (called classes) allow:
functions to be associated with the class only allow certain functions to access the internals of the class allow the user to re-define existing functions (for example, input and output) to work on class
Comments in C++
Can use C form of comments /* A Comment */ Can also use // form:
when // encountered, remainder of line ignored works only on that line
Examples:
void main() { int I; // Variable used in loops char C; // No comment comment
Variable Declarations
In C++, variable declarations are not restricted to the beginnings of blocks (before any code)
you may interleave declarations/statements as needed it is still good style to have declarations first
Example
void main() { int I = 5; printf(Please enter J: ); int J; // Not declared at the start scanf(%d,&J);
Example
for (int I = 0; I < 5; I++) printf(%d\n,I);
Variable exists only during for loop (goes away when loop ends)
void*
In C it is legal to cast other pointers to and from a void * In C++ this is an error, to cast you should use an explicit casting command Example:
int N; int *P = &N; void *Q = P; // illegal in C++ void *R = (void *) P; // ok
NULL in C++
C++ does not use the value NULL, instead NULL is always 0 in C++, so we simply use 0 Example:
int *P = 0; // equivalent to // setting P to NULL
enum in C++
Enumerated types not directly represented as integers in C++
certain operations that are legal in C do not work in C++
Example:
void main() { enum Color { red, blue, green }; Color c = red; c = blue; c = 1; // Error in C++ ++c; // Error in C++
bool
C has no explicit type for true/false values C++ introduces type bool (later versions of C++)
also adds two new bool literal constants true (1) and false (0)
Other integral types (int, char, etc.) are implicitly converted to bool when appropriate
non-zero values are converted to true zero values are converted to false
bool operations
Operators requiring bool value(s) and producing a bool value:
&& (And), || (Or), ! (Not)
Relational operators (==, !=, <, >, <=, >=) produce bool values Some statements expect expressions that produce bool values:
if (boolean_expression) while (boolean_expression) do while (boolean_expression) for ( ; boolean_expression; )