Lesson 2 of 31

Variables and Types

Variables and Types

C is a statically typed language. Every variable must be declared with a type before use.

The Enterprise's main computer stores data in specific types too -- just like C requires explicit type declarations. No ambiguity allowed on the bridge.

Basic Types

TypeSizeDescription
int4 bytesInteger (at least 16 bits, typically 32)
char1 byteSingle character / small integer
long8 bytesLong integer (at least 32 bits, typically 64)
float4 bytesSingle-precision floating point
double8 bytesDouble-precision floating point

Declaring Variables

int age = 25;
char letter = 'A';
long big = 1000000000L;

Format Specifiers

Use the matching format specifier when printing:

int x = 42;
printf("x = %d\n", x);

char c = 'Z';
printf("c = %c\n", c);

long n = 999;
printf("n = %ld\n", n);

Const Correctness

The const qualifier tells the compiler a value must not be modified. This helps prevent bugs and makes your intent clear to other programmers.

Const variables cannot be reassigned:

const int MAX = 100;
// MAX = 200;  // ERROR: assignment of read-only variable

Const pointers -- the placement of const matters:

const int *p1;       // pointer to const int: can't modify *p1
int *const p2 = &x;  // const pointer to int: can't modify p2 itself
const int *const p3 = &x;  // both: can't modify *p3 or p3

Read it right-to-left: const int *p means "p is a pointer to an int that is const."

Const function parameters signal that a function won't modify the data:

void print_value(const int *p) {
    printf("%d\n", *p);  // OK: reading
    // *p = 10;          // ERROR: can't modify through const pointer
}

This is especially important for string parameters -- use const char * when a function only reads a string.

Your Task

Declare three variables: an int set to 42, a char set to 'Z', and a long set to 100. Print them each on a separate line using the format shown in the expected output.

TCC compiler loading...
Loading...
Click "Run" to execute your code.