Broad Network


Scalar Type, Multiple Variable Declaration and Casting in C

Part 13 of Complete C Course

Foreword: Scalar Type, Multiple Variable Declaration and Casting in C

By: Chrysanthus Date Published: 3 Jun 2024

Introduction

Some different data types can be grouped into a larger category, called the scalar type. The char type, the integer type, the float type, the double and the pointer type form the larger category, called the scalar type. Arrays and structures form another larger category, called the aggregate type - see below.

More than one character identifier, can be declared in one statement, as in the following code segment:

        char ch1, ch2, ch3;
        ch1 = 'A';
        ch2 = 'B';
        ch3 = 'C';
        printf("%c, %c, %c\n", ch1, ch2, ch3);

The output is: A, B, C . The first statement declares the character identifiers: ch1, ch2 and ch3. The second, third and fourth statements assign their values (initialize). Note the arrangement of text in the first argument of the printf() function. Note the corresponding second, third and fourth arguments of the printf() function.

More than one float identifiers can be declared in one statement, as in the following code segment:

        float ft1, ft2, ft3;
        ft1 = 1.1;
        ft2 = 2.2;
        ft3 = 3.3;
        printf("%f, %f, %f\n", ft1, ft2, ft3);

The output is: 1.100000, 2.200000, 3.300000 . The first statement declares the float number identifiers: ft1, ft2 and ft3. The second, third and fourth statements assign their values (initialize). Note the arrangement of text in the first argument of the printf() function. Note the corresponding second, third and fourth arguments of the printf() function.

Casting Operation
A float can be converted into an integer. That is an example of casting operation. What happens in this case is that, the decimal digit is simply truncated (no rounding).  As another example, a char can be converted to its ASCII decimal integer value. Casting means converting an object from one type, to a similar type. The following program illustrates this for float and char:

    #include <stdio.h>

    int main(int argc, char *argv[])
    {
        float flt = 2.6;
        int it = (int)flt;

        char ch = 'E';
        int asciiCode = (int)ch;
        
        printf("%i\n", it);
        printf("%i\n", asciiCode);
        
        return 0;
    }

The output is 2 and 69 with each integer on its own line. In the code, the new type is put in parentheses, followed by the identifier of the given value (type).




Related Links

More Related Links

Cousins

BACK NEXT

Comments