C Variable Values

1. What is a Variable Value?

  • A variable value is the actual data stored in the memory location represented by a variable.

  • Variables can hold different values during program execution.

Example:

#include <stdio.h>

int main() {
int age = 25; // Variable 'age' has value 25
printf("Age: %d\n", age);

age = 30; // Changing the value of 'age'
printf("New Age: %d\n", age);

return 0;
}

Output:

Age: 25
New Age: 30

2. Initial Value vs. Assigned Value

  1. Initialization → Assigning a value when the variable is declared:

int x = 10; // x is initialized with 10
  1. Assignment → Giving a value to a variable after declaration:

int x;
x = 20; // value assigned later

3. Changing Variable Values

  • Variables in C are mutable, meaning you can update their values anytime in the program.

int counter = 0;
counter = counter + 1; // Increase value
  • Can also use compound operators:

counter += 5; // counter = counter + 5
counter -= 2; // counter = counter - 2
counter *= 3; // counter = counter * 3
counter /= 2; // counter = counter / 2

4. Example with Multiple Variables

#include <stdio.h>

int main() {
int a = 10, b = 20;
float pi = 3.14;
char grade = 'A';

printf("a = %d, b = %d\n", a, b);
a = 15; // changing value
b = a + b;
printf("Updated a = %d, b = %d\n", a, b);
printf("Pi = %.2f, Grade = %c\n", pi, grade);

return 0;
}

Output:

a = 10, b = 20
Updated a = 15, b = 35
Pi = 3.14, Grade = A

5. Default Values of Variables

  • In C, local variables are not initialized by default.

  • They may contain garbage (random) values until you assign something.

  • Global and static variables are automatically initialized to 0 (for numbers) or NULL (for pointers).

#include <stdio.h>

int globalVar; // default 0

int main() {
int localVar; // garbage value
printf("Global: %d\n", globalVar);
printf("Local: %d\n", localVar);
return 0;
}


6. Key Points

  1. Variable value can change anytime after declaration.

  2. Always initialize local variables to avoid garbage values.

  3. Use assignment operators for easy value updates.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *