'Tips/C++ Eng'에 해당하는 글 26건

Enumerations

Tips/C++ Eng 2015.10.27 16:16

In the topics on variables and constants, it was noted that anytime you want to create a value for use in a program, where the value should never change, you used a constant. An enumeration can be considered a way to create what are known as symbolic constants. The most common example is to use an enum to define the day of the week. There are only seven possible values for days of the week, and you can be reasonably certain that these values will never change.

To create an enum, you declare it in your code file with the following syntax, which demonstrates creating an enum called Day, that contains the days of the week:

enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

By default enum values start at 0 and each successive member is increased by a value of 1. As a result, the previous enum 'Day' would contain the values:

  • Sunday = 0
  • Monday = 1
  • Tuesday = 2
  • etc.

You can change the default by specifying a starting value for your enum as in the following example.

enum Day { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

In this example, Sunday is given the value 1 instead of the default 0. Now Monday is 2, Tuesday is 3, etc.

The keyword enum is used to specify the "type" that the variable Day will be. In this case, an enumeration type. Consider the following code sample:

enum Day { Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }; 
Day payDay; 
payDay = Thursday; 
cout << payDay << endl;

The first line defines the enumeration Day and assigns seven values to the enum. Sunday is listed as the first day of the week and is initialized with the value one.

The second line declares a new variable called payDay which is of the Day enum type. In the third line,payDay is assigned a value from the list of values, in this case Thursday. Finally, the last line outputs the value of payDay to the console window. If you run this code, you will notice that the last line outputs 5 and not Thursday. Internally, the constants in the enum are used as numbers and not as the textual representation you assign to them.

What is the size of this enum, in bytes?

더보기


This contents come from edx : Introduction to C++ 


저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Introducing Operators  (0) 2015.11.01
Unions Quiz  (0) 2015.10.27
Enumerations  (0) 2015.10.27
Unions  (0) 2015.10.27
Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

Unions

Tips/C++ Eng 2015.10.27 16:03

A union, in C++, is similar to a structure in that it can store multiple, disparate data types. The differentiation is that a union can only store one piece of data at a time. What does that signify? It's best represented using an example.

union numbericUnion 

     int intValue; 
     long longValue; 
     double doubleValue; 
}; 
numbericUnion myUnion; 
myUnion.intValue = 3; 
cout << myUnion.intValue << endl; 
myUnion.doubleValue = 4.5; 
cout << myUnion.doubleValue << endl; 
cout << myUnion.intValue; cout << endl;

In this example, we define a union called numericUnion and then create a variable of that type, calledmyUnion. We first assign the value 3 to the intValue field and then output it. Next we assign the value 4.5 to the doubleValue field and output that. The example shows how the union works when on the second to last line, we try to output the value for intValue again. In the output, it results in 0 rather than 3. The reason is that once we assign a value to doubleValue, what was contained in intValue is lost. The union can only store a value in one of its fields at a time. [한 필드에 자신의 값만 저장할 수 있다.]

Why use a union over a struct if it can only hold one piece of data at a time? Consider a situation where you are programming an application that will run on a device with limited memory. You would like to use a data type that can support multiple types internally like a struct, but not necessarily all at the same time. For example, part numbers for components in manufacturing where the part number may be a number or perhaps a string, depending on the manufacturer of the part. In this case, you could use the union to represent a numeric and a string data type internally but only assign the proper data type based on the part number.

This contents come from edx course : Introduction to C++


저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Unions Quiz  (0) 2015.10.27
Enumerations  (0) 2015.10.27
Unions  (0) 2015.10.27
Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

Arrays can store multiple pieces of data in one compound data type but recall, the data types must all be of the same type. If that is the case, how might you store multiple pieces of data in one type, where the individual pieces are of different data types? For example, let's say that we want to store information about a coffee bean. We might want to store information about the bean type, its strength, and perhaps which country it originated from. In this case, we could use all strings to store that information but what if the strength was intended to be a number from 1 to 10. In this case, we would want to store two strings and one integer in our coffee bean data type.

We haven't covered classes yet, which is another data type we could use, but instead, we will use a structure (struct) to store this information. Structures are known as user-defined types. You define the struct by giving it a name and then adding the member data types as in the following example:

struct coffeeBean 

     string name; 
     string country; 
     int strength; 
};

Recall that in order to use the string data type in our struct, the C++ file that contains the struct must include the string header file. This code snippet also assumes that using namespace std; has also been included.

Once we have defined the structure, we can then use it in our code the same as any other data type. To use the coffeeBean struct in your code, you simply declare a new variable of that type as shown in this example.

struct coffeeBean 

     string name; 
     string country; 
     int strength; 
}; 

coffeeBean myBean = { "Strata", "Columbia", 10 }; 
coffeeBean newBean; 
newBean.name = "Flora"; 
newBean.country = "Mexico"; 
newBean.strength = 9; 
cout << "Coffee bean " + newBean.name + " is from " + newBean.country << endl;

You can assign values to a struct using one of the methods seen here. For myBean, we assign values in the curly braces while for newBean, we use the dot notation. You can also access the values of the the struct members using the dot notation as well, shown in the cout statement at the end.

This contents come from edx : Introduction to C++

저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Enumerations  (0) 2015.10.27
Unions  (0) 2015.10.27
Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
int main()
{
    char isAString[6= { 'H''e''l''l''o''\0' };
    char isNotAString[5= { 'H''e''l''l''o' };
    std::cout << isAString << std::endl;
    std::cout << isNotAString << std::endl;
     
 
    return 0;
}
 
 
 
 
cs


This makes error !!


저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Unions  (0) 2015.10.27
Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14
Narrowing Conversion  (0) 2015.10.13

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

Strings are a series of characters. C++ represents strings in one of two ways. The first maintains backward compatibility with the C language and represents the string as a character array. There is one aspect to a C-style string that is important to note. The last character of every string you store is the null character string, typically represented by the ASCII code for 0 which is \0. This is necessary so that the compiler knows when the string ends. An example demonstrates a C-style string stored in a character array:

char isAString[6] = { 'H', 'e', 'l', 'l', 'o', '\0'}; 
char isNotAString[5] = { 'H', 'e', 'l', 'l', 'o'}; 
cout << isAString << endl; 
cout << isNotAString << endl;

The most common mistake made by users of the C-style string is to forget to make the char array large enough to accommodate the \0 character, but also forgetting include the \0. In the previous example, a programmer might think that an array of size 5 would be large enough to contain Hello because that's how many characters are in the word. However, the null character would not be included in the second array, which could result in errors in code that uses this array. The reason is that C++ does not consider the isNotAString array to be a string.

Consider the output displayed in Figure 2.1. Note that the first output correctly terminates because C++ encountered the null (\0) character. The second did not terminate and output the contents of adjacent memory.


This contents come from edx : Introduction to C++ 

저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Structure [구조체]  (0) 2015.10.21
String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14
Narrowing Conversion  (0) 2015.10.13
Type Conversions & Converting Data  (0) 2015.10.12

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

Accessing Data in an Array

You can access data in an array in several ways, such as by specifying the index of a specific element that you require or by iterating through the entire array and returning each element in sequence.

The following code example uses an index to access the element at index two.

//Accessing Data by Index
int[] oldNumbers = { 1, 2, 3, 4, 5 };

//number will contain the value 3
int number = oldNumbers[2];

Note: Arrays are zero-indexed, so the first element in any dimension in an array is at index zero. The last element in a dimension is at index N-1, where N is the size of the dimension. If you are using some other languages, such as C#, and you attempt to access an element outside this range, the C# runtime will throw an exception (error). C++ doesn't offer such protection. If you attempt to access an element that is outside the bounds of your array, you will still return data, but you have no idea what that data is.

The reason for this is because an array is simply a pointer to a memory location. The first element of the array is the starting memory address for the entire array. If you have an array of integer data types, then the number of the elements multiplied by the size of the int data type on your system, determines how much memory is used by the array, and at the same time, permits the access of the elements in the array by performing math on the memory address to get at the required element. If you attempt to access oldNumbers[5], the program will simply return the data found at the memory address that is the next memory address location beyond the last array element. This can be a dangerous situation and is in fact, the result of some security issues found in software.

You can also iterate through an array by using a for loop. You will cover loops in module 3 so don't worry if you don't completely understand this example at this time. Essentially, the for loop starts at 0 and repeats the portion in the curly braces {} for each of the five steps in the loop.

The following code example shows how to use a for loop to iterate through an array.

//Iterating Over an Array
int[] oldNumbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < 5; i++)
{
     int number = oldNumbers[i];
     ...
}

This contents come from edx : introduction to C++

저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

String Error in C++  (0) 2015.10.18
Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14
Narrowing Conversion  (0) 2015.10.13
Type Conversions & Converting Data  (0) 2015.10.12
Const  (0) 2015.10.12

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

A narrowing conversion will result in some data loss. [True/False]

Why?

A narrowing conversion, such as going from a double to an int type, can result in a loss of some data due to the size limits on the int data type. Any conversion that assigns a larger data type to a smaller data type, could result in data loss. Even from a float to a double, the fractional portion will be lost.


저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Strings [문자형]  (0) 2015.10.18
Accessing Data in an Array  (0) 2015.10.14
Narrowing Conversion  (0) 2015.10.13
Type Conversions & Converting Data  (0) 2015.10.12
Const  (0) 2015.10.12
Choosing Data Types  (0) 2015.10.11

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret

Casting refers to converting one data type to another. Some data conversions are not possible while some are possible but result in data loss. C++ can perform many conversions automatically, what is known as implicit casting or implicit conversion. For example, attempting to convert a smaller data type to larger data type as shown here:

int myInt = 12; long myLong;

myLong = myInt;

In the first line, we declare an integer data type and assign it a value of 12. The next line declares a long data type and in the third line, we assign the integer data type value to the long data type. C++ automatically converts the data type for you. This is known as a widening conversion. Some programmers also call this an expanding assignment. We are expanding or widening the data type to a larger one. In this case, there is no loss in data. The following table highlights some potential data conversion problems.

ConversionPotential Issues
Large floating point type to small
floating point type
Loss of precision and/or the starting value
might be out of range for the new type
Floating point type to integer typeLoss of the fractional component of the floating
point type and/or out of range
Bigger integer type to smaller integer typeStarting value may be out of range for the new type

This table only deals with numeric data type conversions. There are other conversion types such as from character to numeric or numeric to character, or among character types. C++ also uses the boolean type that represents true or false. If you assign a zero value to a bool variable, it will be converted to false. Any non-zero value is converted to true.

When you want to explicitly perform a conversion or cast, you can use the type cast features of C++. For example, the previous widening conversion in the int to long cast was implicit but you can also tell the compiler that you are know what you are doing by using the type cast statement as in:

long myLong = (long)myInt;

// or you can use this version as well

long myLong = long(myInt);

C++ also provides a cast operator that is more restrictive in its usage. This in the form static_cast (type).This static cast operator can be used for converting numeric values or to numeric values. 

As an example:

char ch;

int i = 65;

float f =2.5;

double dbl;

ch = static_cast<char>(i);       //int to char

dbl = static_cast<double>(f);  //float to double


This contents come from edx : introduction to c++ course.

저작자 표시
신고

'Tips > C++ Eng' 카테고리의 다른 글

Accessing Data in an Array  (0) 2015.10.14
Narrowing Conversion  (0) 2015.10.13
Type Conversions & Converting Data  (0) 2015.10.12
Const  (0) 2015.10.12
Choosing Data Types  (0) 2015.10.11
Other Data Types  (0) 2015.10.11

WRITTEN BY
Profile
비타오백
Enjoy your stage!

받은 트랙백이 없고 , 댓글이 없습니다.
secret