2 CPP Basic More
2 CPP Basic More
| HOME
enum Color {
RED, GREEN, BLUE
} myColor; // Define an enum and declare a variable of the enum
......
myColor = RED; // Assign a value to an enum
Color yourColor;
yourColor = GREEN;
The enumerators are represented internally as integers. You have to use the names in assignment, not the numbers. However, it will be
promoted to int in arithmetic operations. By default, they are running numbers starting from zero. You can assigned different numbers, e.g.,
enum Color {
RED = 1, GREEN = 5, BLUE
};
To print the enumerator names, you may need to define a array of string, indexed by the enumerator numbers.
2. *Structure ( struct )
A struct (structure) is a user-defined data structure that can be used to hold a set of variables of different types (called members) . To
defined a struct:
struct StructName {
type1 var1;
type2 var2;
.......
}; // need to terminate by a semi-colon
struct is an intermediate step towards Object-oriented Programming (OOP). In OOP, we use class that is an user-defined structure
containing both data members and member functions.
Notes:
You can declare and initialize an instance of struct as shown in Line 11 and Line 14.
To access members of a struct, use the dot (.) operator.
p1 at (0,3)
p2 at (4,0)
Rectangle top-left at (0,3)
Rectangle bottom-right at (4,0)
C++ struct s
C++ evolves the C's structs into OOP classes. The legacy C's structs contain public data members. C++ structs, like classes, may
contain access specifiers (public, private, protected), member functions, constructor, destructor and support inheritance. The only
difference for C++'s structs and classes is the struct's members default to public access while class members default to private
access, if no access specifier is used. Also, C++ structs default to public-inheritance whereas classes default to private-inheritance.
3. *Bit-wise Operations
4. *More on Functions
1 // TestInlineFunction.cpp
2 #include <iostream>
3 using namespace std;
4
5 inline int max(int n1, int n2) {
6 return (n1 > n2) ? n1 : n2;
7 }
8
9 int main() {
10 int i1 = 5, i2 = 6;
11 cout << max(i1, i2) << endl; // inline request to expand to (i1 > i2) ? i1 : i2
12 return 0;
13 }
The expanded statement is faster than invoking a function call. The trade-off is bigger code size.
Inline is just a recommendation. Compiler may not support or may ignored the recommendation.
Inline function is preferred over macro expansion, as seen from the above example.
1 /*
2 * TestEllipses.cpp
3 */
4 #include <iostream>
5 #include <cstdarg>
6 using namespace std;
7
8 int sum(int, ...);
9
10 int main() {
11 cout << sum(3, 1, 2, 3) << endl; // 6
12 cout << sum(5, 1, 2, 3, 4, 5) << endl; // 15
13
14 return 0;
15 }
16
17 int sum(int count, ...) {
18 int sum = 0;
19
20 // Ellipses are accessed thru a va_list
21 va_list lst; // Declare a va_list
22 // Use function va_start to initialize the va_list,
23 // with the list name and the number of parameters.
24 va_start(lst, count);
25 for (int i = 0; i < count; ++i) {
26 // Use function va_arg to read each parameter from va_list,
27 // with the type.
28 sum += va_arg(lst, int);
29 }
30 // Cleanup the va_list.
31 va_end(lst);
32
33 return sum;
34 }
1 // TestScopeResolutionOperator.cpp
2 #include <iostream>
3 using namespace std;
4
5 // Global variable
6 int x = 5;
7
8 int main() {
9 // A local variable having the Same name as a global variable,
10 // which hides the global variable
11 float x = 55.5f;
12
13 // Local
14 cout << x << endl;
15
16 // Use unary scope resolution operator to retrieve the global variable
17 cout << ::x << endl;
18
19 return 0;
20 }
"-o test test.cpp" are called command-line arguments. Each of the argument is a string, all the arguments form a string array, and
passed into the main() function of the program.
To process command-line argument, the main() function shall use this header:
The second parameter char *argv[] captures the string array, while the first parameter capture the size of the array, or the number of
arguments.
For example,
1 /*
2 * Arithmetic.cpp
3 * Usage: Arithmetic num1 num2 operator
4 */
5 #include <iostream>
6 #include <cstdlib>
7 using namespace std;
8
9 int main(int argc, char *argv[]) {
10
11 if (argc != 4) {
12 cout << "Usage: Arithmetic num1 num2 operator" << endl;
13 exit(1);
14 }
15
16 int operand1 = atoi(argv[1]); // Parse string to int
17 int operand2 = atoi(argv[2]); // Parse string to int
18 char op = argv[3][0]; // Extract first character only
19
20 switch (op) {
21 case '+':
22 cout << operand1 << " + " << operand2 << " = " << operand1 + operand2 << endl;
23 break;
24 case '-':
25 cout << operand1 << " - " << operand2 << " = " << operand1 - operand2 << endl;
26 break;
27 case '*':
28 cout << operand1 << " * " << operand2 << " = " << operand1 * operand2 << endl;
29 break;
30 case '/':
31 cout << operand1 << " / " << operand2 << " = " << operand1 / operand2 << endl;
32 break;
33 default:
34 cout << "Unknown operator" << endl;
35 exit(1);
36 }
37
38 return 0;
39 }
5. *More on Preprocessor Directives
A preprocessor directive begins with # (e.g., "#include <stdio.h>", "#define PI 3.14256295"). When you compile a C/C++ program,
these commands will be pre-processed to produce the source file for the actual compilation (e.g., to include a specific header file in this
program or to define a certain macro substitution).
A preprocessor command is NOT a C statement, and it does NOT end with a semi-colon.
#include : #include is most commonly-used to include a header file into this source file for subsequent compilation. The syntax is as
follows:
// Syntax // Examples
#include header_file #include <stdio.h> // Search the compiler's include paths
#include "myHeader.h" // Search the current directory first
#define , #undef : #define can be used to define a macro. When the macro pattern appears subsequently in the source codes, it will be
replaced or substituted by the macro's body. Macro may take parameters. You can use #undef to un-define a macro.
Two common mistakes when using a #define command for macro substitution are:
#define PI = 3.14159265 // 1
#define PI 3.14159265; // 2
In case 1, the macro name " PI" is defined to be " = 3.14159265" (with the leading '=' sign). In case 2, it is " 3.14159265;" (with a tailing
';'). These will certainly trigger errors in your program during the actual compilation.
#define is also commonly-used in define a macro name with an empty body, to be used in the conditional directives such as #ifdef and
#ifndef.
#ifdef , #ifndef , #if , #elif , #endif : Conditional directives can be used to control the sections of program send for compilation:
// conditional if else
#if expression #if 1 (always true), #if 0 (always false)
......
#elif condition
......
#else
......
#endif
For example,
#ifndef SIZE
#define SIZE 1000
#endif
......
For example, in a header file (e.g., myHeader.h), the following directive are often used to prevent this header from included more than once
in a source file.
#ifndef __MY_HEADER
#define __MY_HEADER
#endif
......
#pragma : The directive #pragma can be used to direct compiler for system-dependent information. A common usage is:
#ifdef _MSC_VER // This pragma comment works on MS Visual C++ only, NOT Gcc
#pragma comment(lib, "opengl32.lib") // Direct compiler to include this library, same as -l command-line option
#endif
Others: Other directives include #errors and #line, which are not commonly used.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan ([email protected]) | HOME