@agustfricke
C memory managmentBasics

Variables & Basic Types

Variables & Basic Types in C language

Basic Types in C

  • int - An integer number (e.g., 42, -7, 1337).
  • float - A floating-point number, used for decimals (e.g., 3.14, 0.007).
  • char - A single character, written with single quotes (e.g., 'A', 'Z', '#').
  • char * - A pointer to a sequence of characters (a string), written with double quotes (e.g., "Hello", "C programming").
#include <stdio.h>

int main() {
  int cool_number = 73;
  char z_letter = 'Z';
  float pi = 3.14;
  char *bare = "Bare Metal";

  printf("Cool number: %d\n", cool_number);
  printf("Letter here: %c\n", z_letter);
  printf("Pi number: %f\n", pi);
  printf("%s\n", bare);
  return 0;
}

Printing Variables

We have to tell C how we want particular values to be printed using "format specifiers".

Common format specifiers are:

  • %d - digit integer.
  • %c - character.
  • %f - floating point number.
  • %s - string char *.

In C, the newline character \n is used to move the cursor to the beginning of the next line.

#include <stdio.h>

int main() {
  char * name = "agustfricke";
  char num_repos = 'Z';

  printf("Your GitHub username is %s, and you have %d repositories on GitHub.\n", name, num_repos);
  return 0;
}

Compilation - Types

In C, changing the type of an existing variable is not allowed:

int main() {
    char *port = "22";
    port = 22; // error ■ Incompatible integer to pointer conversion assigning to 'char *' from 'int'
}

However, a variable's value can change:

int main() {
    int port = 22;
    port = 80; // ok
    port = 443; // still ok
}
#include <stdio.h>

int main() {
  int port = 22;
  port = 80;
  printf("%d is the http port\n", port);
  return 0;
}

Constants

So a variable's value can change:

int main() {
    int age = 19;
    age = 20; // this is ok
}

But what if we want to create a value that can't change? We can use the const type qualifier.

int main() {
    const int pi = 3.14;
    x = 4.13; // error
}