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

2 CPP Basic More

The document discusses several C++ programming concepts: 1. It describes enums, structs, and bitwise operations. Enums define a set of named constants, structs define user-defined data structures, and bitwise operations manipulate bits. 2. It also covers functions, including inline functions to avoid function call overhead, and function arguments through ellipses. 3. The document provides examples of using enums to define colors, structs to define points and rectangles, and bitwise operations on bits.

Uploaded by

manju_achari_c
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)
39 views

2 CPP Basic More

The document discusses several C++ programming concepts: 1. It describes enums, structs, and bitwise operations. Enums define a set of named constants, structs define user-defined data structures, and bitwise operations manipulate bits. 2. It also covers functions, including inline functions to avoid function call overhead, and function arguments through ellipses. 3. The document provides examples of using enums to define colors, structs to define points and rectangles, and bitwise operations on bits.

Uploaded by

manju_achari_c
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
You are on page 1/ 7

yet another insignificant programming notes...

| HOME

TABLE OF CONTENTS (HIDE)


1. *Enumeration (enum)

C++ Programming Language 2. *Structure (struct)


3. *Bit-wise Operations
3.1 Bit-wise Logical Operations

More Basics 3.2 Bit-Shift Operations


4. *More on Functions
4.1 Inline Functions
4.2 Ellipses (...)
4.3 Scope Resolution Operator
This chapter is written for completeness. Novices may slip this chapter.
4.4 Command-Line Arguments
5. *More on Preprocessor Directives
1. *Enumeration ( enum )
An enum is a user-defined type of a set of named constants, called enumerators. An enumeration define the complete set of values that can
be assigned to objects of that type. For example,

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.

Example: Deck of Card


[TODO]

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.

Example: struct Point


1 /* Testing struct (TestStruct.cpp) */
2 #include <iostream>
3 using namespace std;
4
5 struct Point {
6 int x;
7 int y;
8 };
9
10 int main() {
11 Point p1 = {3, 4}; // declare and init members
12 cout << "(" << p1.x << "," << p1.y << ")" << endl; // (3,4)
13
14 Point p2 = {}; // declare and init numbers to defaults
15 cout << "(" << p2.x << "," << p2.y << ")" << endl; // (0,0)
16 p2.x = 7;
17 p2.y = 8;
18 cout << "(" << p2.x << "," << p2.y << ")" << endl; // (7,8)
19 return 0;
20 }

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.

Example: struct Person


A struct can contains members of different types.

1 /* Testing struct (TestStructPerson.cpp) */


2 #include <iostream>
3 #include <string>
4 using namespace std;
5
6 struct Person {
7 string name;
8 int age;
9 double height;
10 double weight;
11 };
12
13 int main() {
14 Person peter = {"Peter Jone", 18, 180.5, 70.5};
15 cout << "Name: " << peter.name << endl;
16 cout << "Age: " << peter.age << endl;
17 cout << "Height: " << peter.height << endl;
18 cout << "weight: " << peter.weight << endl;
19 return 0;
20 }

Example: structs Point and Rectangle


1 /*
2 * Testing struct (TestStruct.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 struct Point {
8 int x, y;
9 };
10
11 struct Rectangle {
12 Point topLeft;
13 Point bottomRight;
14 };
15
16 int main() {
17 Point p1, p2;
18 p1.x = 0; // p1 at (0, 3)
19 p1.y = 3;
20 p2.x = 4; // p2 at (4, 0)
21 p2.y = 0;
22
23 cout << "p1 at (" << p1.x << "," << p1.y << ")" << endl;
24 cout << "p2 at (" << p2.x << "," << p2.y << ")" << endl;
25
26 Rectangle rect;
27 rect.topLeft = p1;
28 rect.bottomRight = p2;
29
30 cout << "Rectangle top-left at (" << rect.topLeft.x
31 << "," << rect.topLeft.y << ")" << endl;
32 cout << "Rectangle bottom-right at (" << rect.bottomRight.x
33 << "," << rect.bottomRight.y << ")" << endl;
34
35 return 0;
36 }

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

3.1 Bit-wise Logical Operations


Bit-wise operators perform operation on one or two operands on a bit-by-bit basis.

Operator Description Usage


& Bit-wise AND expr1 & expr2
| Bit-wise OR expr1 | expr2
! Bit-wise NOT !expr
^ Bit-wise XOR expr1 ^ expr2

Compound operator &=, |= and ^= are also available.

3.2 Bit-Shift Operations


Bit-shift operators perform left or right shift on an operand by a specified number of bits. Left-shift is padded with zeros. Right-shift may
padded with zero or sign-bit, depending on implementation.

Operator Usage Description


<< operand << number Left-shift and padded with zeros
>> operand >> number Right-shift

4. *More on Functions

4.1 Inline Functions


Function call has its overhead (handling the argument, managing function stack, branch and return). For simple and short functions, you may
use inline functions to remove the function call overhead. The keyword inline (before the function's return-type) suggest to the compiler to
"expand" the function code in place, instead of performing a function call. For example,

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 compiler may expand line 11 as:

cout << (i1 > i2) ? i1 : i2 << endl;

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 vs. #define Macro


In C, you can use the #define preprocessor directive to define a macro with argument, which would then be expanded during pre-
processing. For example,
1 /* Test #define macro (TestMacro.cpp) */
2 #include <iostream>
3 using namespace std;
4
5 #define SQUARE(x) x*x // Macro with argument
6
7 inline int square(int x) { return x*x; } // inline function
8
9 int main() {
10 cout << SQUARE(5) << endl; // expand to 5*5 (25)
11 int x = 2, y = 3;
12 cout << SQUARE(x) << endl; // expand to x*x (4)
13
14 // Problem with the following macro expansions
15 cout << SQUARE(5+5) << endl; // expand to 5+5*5+5 - wrong answer
16 cout << square(5+5) << endl; // Okay square(10)
17 cout << SQUARE(x+y) << endl; // expand to x+y*x+y - wrong answer
18 cout << square(x+y) << endl; // Okay
19 // can be fixed using #define SQUARE(x) (x)*(x)
20
21 cout << SQUARE(++x) << endl; // expand to ++x*++x (16) - x increment twice
22 cout << x << endl; // x = 4
23 cout << square(++y) << endl; // Okay ++y, (y*y) (16)
24 cout << y << endl; // y = 4
25 }
26

Inline function is preferred over macro expansion, as seen from the above example.

4.2 Ellipses (...)


Ellipses (...) can be used as the last parameter of a function to denote zero or more arguments of unknown type. The compiler suspends
type checking for these parameters. For 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 }

4.3 Scope Resolution Operator


The symbol :: is known as scope resolution operator. If a global variable is hidden by a local variable of the same name (of course not
recommended), you could use the scope resolution operator to retrieve the hidden global variable. For example,

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 }

4.4 Command-Line Arguments


You may include arguments in the command-line, when running a program, for example,

$ gcc -o test test.cpp

"-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:

int main(int argc, char *argv[]) { ...... }

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.

// Define a macro substitution // Example


#define marco_name macro_value #define PI 3.14159256

// Define a macro with parameters // Example


#define marco_name(args) marco_definition #define square(x) (x*x)
#define max(x,y) ((x > y) ? x : y)
#define REP(i,n) for (i = 0; i < n; ++i)
#define FOR(i,a,b) for (i = a; i < b; ++i)

// Un-define a macro name // Example


#undef marco_name #undef PI

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:

// if the marco_name is defined // Examples


#ifdef macro_name
......
#endif

// if the macro_name is NOT defined


#ifndef macro_name
......
#endif

// 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.

Link to "C++ References & Resources"

Latest version tested: Gygwin/MinGW GCC 4.6.2


Last modified: May, 2013

Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan ([email protected]) | HOME

You might also like