CodeBlanks Logo Icon CodeBlanks

Variable assignment

Learn to assign and initialize values to variables.

Variable assignment

Assignment means giving a value to a variable. In C the assignment operator is =. After declaring a variable, you can assign new values as many times as you want:

int x = 5;
x = 10;
x = 20;

Each assignment overwrites the old value with the new one. = means assignment, not equality; for equality use ==.

Type mismatch

When assigning with mismatched types, C silently converts, which can cause surprising results:

int x = 3.7;   // x = 3
double y = 5;  // y = 5.0

Converting double to int loses the decimal part. The other way around, the value becomes a decimal automatically. Take warnings seriously; we will see the cast operator in later lessons.

Practice Declare and reassign

Declare an int x with value 5. Then reassign x to 10 and print it with printf using %d.

Starter code

main.c
// declare int x, then assign 10 and print

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int x = 5;
    x = 10;
    printf("%d", x);
    return 0;
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Reassignment

Question
int x = 5;
x ____ 10;
Answer
int x = 5;
x = 10;

Explanation: x = 10; assigns a new value to x.

2 Final value of x

main.c
int x = 5;
x = 10;
printf("%d", x);
  • 10 Correct answer
  • 5
  • 15
  • 50

Explanation: x was set to 5, then reassigned to 10. The final value is 10.

3 Match the operators

Term Meaning
= Assignment
== Equality
+ Addition
- Subtraction

All lessons in Beginner