|< Basic Data Type 1 | Main | Basic Data Type 3 >| Site Index | Download |


 

 

 

 

 

 

MODULE 2_1

C AND C++ CONSTRUCTS AND BASIC DATA TYPES 2

 

 

 

 

 

My Training Period: xx hours

 

Note: ANSI C refers to ISO/IEC C. The source code for this Module is: C & C++ source codes and the practice worksheets: C & C++ basic data types and the C & C++ standard input, scanf()/scanf_s().

 

The C/C++ programming skills that supposed to be acquired:

 

  • Able to understand and use the constant, character and escape sequence.

  • Able to understand and use the C typecasting/promotion.

 

2.6     Escape Sequence

  • The backslash (\) is called an escape character.  When the backslash is encountered, function such as printf() for example, will look ahead at the next character and combines it with the backslash to form an escape sequence, used in functions printf() and scanf().

  • Table 2.6 is the list of the escape sequence.

Code

Code Meaning

\a

Audible bell

\t

Horizontal tab

\b

Backspace

\\

Backslash character

\f

Formfeed

\’

Single quote character

\n

Newline

\"

Double quote character

\r

Carriage return

\0

NULL, ASCII 0

 

Table 2.6:  Escape sequence

  • For general C++ escape sequences are given in the following table.  Besides using the sequence, we also can use their value representation (in hexadecimal) for example \0x0A for newline.

 

Sequence

Value (hex)

Char

What it does

\a

0x07

BEL

Audible bell

\b

0x08

BS

Backspace

\f

0x0C

FF

Formfeed

\n

0x0A

LF

Newline (linefeed)

\r

0x0D

CR

Carriage return

\t

0x09

HT

Tab (horizontal)

\v

0x0B

VT

Vertical tab

\\

0x5c

\

Backslash

\'

0x27

'

Single quote (apostrophe)

\"

0x22

"

Double quote

\?

0x3F

?

Question mark

\o

 -

any

o=a string of up to three octal digits

\xH

 -

any

H=a string of hex digits

\XH

 -

any

H=a string of hex digits

 

Table 2.7: Example of Borland C++ escape sequence

 

2.7    Constants

const  int   day_in_week = 7;

const  float   total_loan  =  1100000.35;

#include <stdio.h>

 

int main()

{

    const double PI = 3.14;

    double rad = 3.5;

   

    printf("Circle area = %.2f\n", PI*rad*rad);

    printf("Circle circumference = %.2f\n", 2*PI*rad);

    printf("Circle diameter = %.2f\n", 2*rad);

   

    // error C3892: 'PI' : you cannot assign to a variable that is const

    // PI = 3.14 + 5.0;

    return 0;

}

 

A sample output:

 

 

 

 

 

 

 

 

 

 

 

 

 

The C const program example

 

2.8    Character and String Constants

'$'    '*'    ' '    'z'    'P'

"Name:   "

"Type of Fruit"

"Day:  "

      "   "

2.9    C Typecasting and Type Promotion

int total, number;

float average;

average = total / number;

average =  (float) total / number;

(type) such as  (int), (float) and (char).

 

  • In an expression containing the data types int and float for example, the ANSI C standard specifies that copies of int operands are made and promoted to float.

  • The cast operator normally used together with the conversion specifiers heavily used with printf()/printf_s() and scanf()/scanf_s().  C’s type promotion rules specify how types can be converted to other types without losing the data accuracy.

  • The promotion rules automatically apply to expressions containing values of two or more different data type in mixed type expression.  The type of each value in a mixed-type expression is automatically promoted to the highest type in the expression.

  • Implicitly, actually, only a temporary version of each new value (type) is created and used for the mixed-type expression, the original value with original type still remain unchanged.

  • Table 2.8 list the data types in order from highest to lowest type with printf and scanf conversion specifications for type promotion

  • From the same table, type demotion, the reverse of type promotion is from lowest to highest.  Type demotion will result inaccurate value such as truncated value.  Program examples for this section are presented in formatted file input/output Module.

  • This issue is very important aspect to be taken care when developing program that use mathematical expressions as well as when passing argument values to functions.

  • C++ has some more advanced features for typecasting and will be discussed in Typecasting Module.

Type

Storage

char, unsigned char, signed char

1 byte

short, unsigned short

2 bytes

int, unsigned int

4 bytes

long, unsigned long

4 bytes

float

4 bytes

double

8 bytes

long double

8 bytes

C type conversion: wide and narrow

#include <stdio.h>

 

int main()

{

      short a = 30;

      int b = 200;

      // use f or F to force to float

      float c = 300.34F;

      double d = 10000.99;

 

      // narrow conversion, compiler warning

      // warning C4244: '=' : conversion from 'double' to 'float', possible loss of data

      c = d + d;

      // warning C4244: '=' : conversion from 'double' to 'float', possible loss of data

      b = c + c;

      printf("c = %.2f\n", c);

      printf("b = %d\n", b);

 

      // explicit conversion, may lose precision, no compiler warning

      c = (float)(d + d);

      d = (double)(c + c);

      printf("\nc = %.2f\n", c);

      printf("b = %d\n", b);

 

      // wide conversion, it is OK

      b = a + a;

      d = c + c;

 

      printf("\nb = %d\n", b);

      printf("d = %.2f\n", d);

 

      return 0;

}

 

A sample output:

C type conversion program example

#include <stdio.h>

 

int main()

{

      float p = 0.0;

      int r = 4, s = 5;

      // integer division gives an integer result. Mixed integer and floating

      // point expression give a  floating point result.

      //

      // make sure the format specifier is matched

      //

      // implicit conversion

      printf("3/2 = %d\n", 3/2);

      printf("\n3.0/2.0 = %.2f\n", 3.0/2.0);

      printf("\n3/2.0 = %.2f\n", 3/2.0);

      printf("\n3.0/2 = %.2f\n", 3.0/2);

      printf("\n1/2 = %d\n", 1/2);

      // explicit conversion

      printf("\n(float)3/2 = %.2f\n", (float)3/2);

      p = r/s;

      // warning C4244: '=' : conversion from 'int' to 'float', possible loss of data

      // fraction part has been discarded

      printf("\np = r/s = %.2f\n", p);

      p = (float)r/s;

      printf("\np = (float)r/s = %.2f\n", p);

      return 0;

}

 

A sample output:

 

C mixed integer and float issue

Data type

printf conversion

specification

scanf conversion

specification

long double

%Lf

%Lf

double

%f

%lf

float

%f

%f

unsigned long int

%lu

%lu

long int

%ld

%ld

unsigned int

%u

%u

int

%d

%d

short

%hd

%hd

char

%c

%c

 

Table 2.8: type promotion precedence, top = highest

Modifier

Description

l (letter ell)

Indicates that the argument is a long or unsigned long.

L

Indicates that the argument is a long double.

h

Indicates that the corresponding argument is to be printed as a short or unsigned short.

 

Table 2.9:  Length modifier

Character

Argument type

Converted to

c

int

single character, after conversion to unsigned char.

d, i

int

Signed decimal notation.

e, E

double

Decimal notation of the form [-]m.de±xx or [-]m.dE±xx, where the number of d is specified by the precision.  6 is the default precision, 0 suppresses the decimal point.  Example: -123.434E-256.

f

double

Decimal notation of the form [-]m.d, where the d is specified by the precision. 6 is the default precision, 0 suppresses the decimal point.  Example: 234.123456.

g, G

double

%e or %E is used if the exponent is less than -4 or greater than or equal to the precision; otherwise %f is used.  Trailing zeros or a trailing decimal point is not printed.

n

int *

The number of characters written so far by this call to printf() is written into the argument.  No argument is converted.

o

int

Unsigned octal notation (without a leading zero).

p

void

Print as a pointer (implementation dependent).

s

char *

Characters from the string are printed until ‘\0’ is reached or until the number of characters indicated by the precision has been printed.

u

int

Unsigned decimal notation.

x, X

int

Unsigned hexadecimal notation (without a leading 0x or 0X), use abcd for 0x or ABCD for 0X.

%

-

No argument is converted; just print a %.

 

Table 2.10:  printf() formatted output conversion

Character

Input Data

Argument Type

c

Characters.

char *.  The next input characters are placed in the indicated array, up to the number given by the width field; 1 is the default.  No ‘\0’ is added.  The normal skip over white space characters is suppressed in this case; use %1s to read the next non-white space character.

d

Decimal integer.

int *

i

Integer.

int *.  The integer may be in octal (with leading 0) or hexadecimal (with leading 0x or 0X).

n

Writes into the argument the number of characters read so far by this call.

int *.  No input is read.  The converted item count is not incremented.

o

Octal integer, with or without leading zero.

int *.

p

Pointer value as printed by printf("%p").

void *.

s

String of non-white space characters, not quoted.

char *.  Pointing to an array of characters large enough to hold the string and a terminating ‘\0’ that will be appended.

u

Unsigned decimal integer.

unsigned int *

x

Hexadecimal integer, with or without leading 0x or 0X.

int *.

e, f, g

Floating-point number.

float *.  The input format for float’s is an optional sign, a string of numbers possibly containing a decimal point, and an optional exponent field containing an E or e followed by a possibly signed integer.

[…]

Matches the longest non-empty string of input characters from the set between brackets.

char *.  A ‘\0’ is appended.  [ ]…] will include ] in the set.

[^…]

Matches the longest non-empty string of input characters not from the set between brackets.

char *.  A ‘\0’ is appended.  [^]…] will include ] in the set.

%

Literal %.

No assignment is made.

 

Table 2.11:  scanf() formatted input conversion

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

Further C and C++ reading and digging:

  1. The ASCII, EBCDIC and UNICODE character sets reference Table can be found here: Character sets Table.
  2. Check the best selling C/C++ books at Amazon.com.

 

 

 

 

 

 

|< Basic Data Type 1 | Main | Basic Data Type 3 >| Site Index | Download |


Program Constructs & Basic Data Type:  Part 1 | Part 2 | Part 3 | Part 4 |