Library tutorials & articles
Programming in C++
- Background of Computer Programming
- C++ Basics
- Type Conversions
- Controlling Execution With Control Struc
- Control Structures and Formatting Output
- Text Files, Strings, Random Numbers, and Member Fu
- In-Depth Look at Functions / Pointers
- Array Type Problems
- Sorting Array Data
- User-Defined Types and Header Files / Graphics
- Classes and Related Topics
Type Conversions
Type Conversion
When dealing with assignment statements and calculations, data types can sometimes
be converted to other data types through something that is called type conversion.
Conversions that take place without the programmer specifically asking for
it are called implicit conversions. Conversions that are requested by the programmer
are called explicit conversions. Programmers run into problems during implicit
conversions because they can be unaware of what is actually happening during
execution of their program until they examine the code very carfully.
|
|
It's pretty clear that programmers can run into problems because of implicit
conversions. However, if you fully understand data types and how they are defined
for certain arithmetic operators, you should be able to avoid them. For instance,
if y and z are float, and a is int, when the statement z = a + y is executed,
the value of a will be stored in a temporary memory location as float for use
in the rest of the statement. Then, the addition is done (in float form) and
finally, the result stored in z. So what happened? [a was implicitly converted
into float during the execution of the statement]
Another form of implicit conversion may take place during assignment, but not
necessarily from a smaller type to a larger type.
Example: int a;
float b = 3.5;
float c = 5.0;
int d = 2;
a = b * c / d;
cout << a; --> 8
What conversion took place in the above example? First of all, d was implicitly
converted to 2.0 during b * c / d. The result of that multiplication and division
is 8.75, but a was declared int, so a was implicitly converted to 8 during
assignment.
|
|
While programmers are unaware of implicit conversions, they are completely
in control of explicit conversions. Explicit conversions, or typecasting, can
come in handy as you will see in later problems. Typecasting can be easily
accomplished and it has a easy to use form which is: type( variable ) where
type is whatever data type you choose and variable is the variable you are
converting. It simply takes the value of variable and converts in into the
type specified.
Example 1: double d;
int k;
d = 12.78;
k = int(d); --> k = 12
d = double(k); --> d = 12.0
Example 2: int m = 10, n = 4, r;
double q;
q = m / n; --> q = 2.0
r = double(m) / n; --> 2
r = m / n; --> 2
q = double(m) / n --> 2.5
Note: q = (double)m / n is equivalent to q = double(m) / n;
Ok, so we have convered assignment statements, arithmitic ops, precedence,
associativity, type conversions, but we haven't covered how programmers compare
expressions in C++. Read on for more about logical and relational expressions...
Logical Expressions
Logcial expressions, somtimes called boolean expressions, are expressions that
return a value of true or false. A ( 1 ) is always associated with a true expression;
a ( 0 ) is always associated with a false expression. There will be many times
when you as a programmer will have to write code to handle certain (true/false)
situations. If an expression is true, then you will issue some command. If
an expression is false, then you will issue another command. Logical expressions
make it possible to test values to see if something is true or false. A relational
expression is a special type of logical expression in which some type of comparison
is performed. The relational operators are >, <, <=, >=, ==, and
!=.
|
|
|
|
Relational Operators
> : greater than
< : less than
>= : greater than or equal to
<= : less than or equal to
== : is equal to
!= : is not equal to
One of the biggest problems many beginning programmers have is distinguishing
between = and ==. Experienced programmers can even run into problems
with these two operators because it is very easy to mistype them when programming.
= is
an operator that is only used for assignment purposes; it does not imply
equality. == (is equal to) is an relational operator that is used to compare
two values
to see if they are equal. Be careful not to use = in relational expressions
when == is needed.
Examples of relational expressions (also logical expressions):
-
a< 2 * b - 7 -
c != -1 -
b > c + 4 * 7
A relational expression is always a logical expression. Logical expressions are either relational expressions or a combination of multiple expressions joined together by the logical operators: &&, ||, and !.
Logical Operators
&& : logical and
|| : logical or
! : logical not
Example of a logical expression (not a relational expression): (a < b) || ( b < c)
If a = 5, b = 3, and c = 10, the result of this expression is 1 (true).
A quick way to tell if an expression is logical but not relational is if
one of the logical operators is being used.
Common Errors:
- Using = (assignment operator) when == is needed.
- Using an expression such as:
midTerm || final == 'A'which needs to be changed tomidTerm == 'A' || final == 'A' - Using an expression such as:
a < b < cwhich needs to be changed toa < b && b < c - Using && when || is needed or vice versa:
Suppose a variable x is being used and x = -1 and x = -99 have special meaning:
if (x != -1 || x != -99)is wrong and needs to be changed toif (x != -1 && x != -99)
In general, the operators have precedence (highest to lowest):
A - arithmetic
R - relational
L - logical
- the one exception is logical not ( ! ), which is done before the arithmetic operators.
Specifically, the overall precedence for operators in this
tutorial is:
1 : !, +, - : (unary)
2 : *, /, %
3 : +, - : (binary)
4 : <, <=, >, >=
5 : ==, !=
6 : &&
7 : ||
Practical Use Example:
Suppose an insurance company offers a discount on auto insurance for students
who have no prior accidents and a GPA of 3.0 or above. What expression
could be used to ask this? numAccidents == 0 && gpa >= 3.0
Most compilers also have a capability called short-circuit evaluation when
evaluating logical expressions. It makes logical operations faster.
If a compound logical expression involves one section that is false and an
AND ( && ) operation
is used, the entire expression must be false. If one section is true
and OR ( || ) is involved, the entire expression must be true.
With expressions out of the way, it's time to see how the flow of programs
can be controlled with C++. Read on for more about the different control
structures...
Related articles
Related discussion
-
conting repeated words
by Slicksim (2 replies)
-
Can somebody help: CAsyncSOcket class (Client-server networking)
by Mohammad Rastkar (3 replies)
-
custom progress bar in a datagridview with threading
by konikula (1 replies)
-
Calling C++ DLL from C#
by Thushan Fernando (1 replies)
Events coming up
-
Dec
6
Developing AJAX Web Applications with Castle Monorail
London, United Kingdom
Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!
Have copied and pasted your program into DevC++, compiled with DevC++ compiler with no errors. I have run the program and been most careful to type in full paths of files but the program ends without doing anything. Sometimes it ends after I have typed in the first path, sometimes the third. I don't know enough to fathom what's wrong with it. Can you advise?
How come when i visit these pages i can never view the examples? is this just to get people really annoyed??
Thank you jawsper for noticing the mistake in the tutorial. In the program example on the second page, you can either remove 'return 0;' or simply place 'system("PAUSE");' directly before the 'return 0;' statement. Currently, I have 'return 0;' before 'system("PAUSE");' and it is causing your compiler to "break" out of program execution before pausing the output stream to display output. I will be sure to remove the error the next time I update the tutorial. Thanks again. Your input is much appreciated.
if you remove the " return 0; " part on the second page of your tutorial, it stops, with the line it doesnt. I use win xp, could it be that whats making it work bad?
This thread is for discussions of Programming in C++.