A2 - variables and data types

data types

characters

#include <stdio.h>


int main() {
    
    // a simple character variable
    char my_char = 'A';
    
    // converting character to its integer value (ASCII)
    int letter_a_code = my_char; // implicit cast
    printf("my converted character is: %d\n", letter_a_code);
    
    // integer value of a numerical character
    char my_num_char = '7';
    int my_num_int = my_num_char - '0'; // -0 converts char to int
    printf("my converted number is: %d\n", my_num_int);

    int my_casted_num = (int) my_num_char;
    printf("my casted number is: %d\n", my_casted_num);

    // convert integer to character
    char converted_a = letter_a_code; // implicit cast
    printf("the character correponding to code %d is: %c\n", letter_a_code, converted_a);

    char explicit_casted_a = (char) letter_a_code; // explicit cast
    printf("explicitlty typecasted: %c\n", explicit_casted_a);

    return 0;
}

integers

unsigned short big_short = 65535 // always positive

#include <limits.h> // for integer constants like INT_MIN, INT_MAX

printf("short int size: %zu bytes\n", sizeof(short)); // shows the size of a short
printf("range %d to %d\n", SHRT_MIN, SHRT_MAX); // the range

floating points

identifiers

identifiers

  • variables or constants used to store data

float my_float; // declaration: 4 bytes of memory allocated on the stack
my_float = 3.14f; // assignment after declaration

double my_double; = 14234.123; // initialization at declaration

const int PI = 3.14; // cannot be reassigned
PI = 9.99; //will throw an error

{
	float another_float = 9.99f; // the variable is valid only inside the current scope 
} // defines a scope

another_float = 3.14f; // throws an error as it is not outside of the scope

// multiple declarations
int a, b, c;
a = 10; b = 20; c = 30;