Assigning Values to Variables
In the C programming language, assigning values to variables involves creating a variable of a specific data type and then assigning a value to it using the assignment operator =. Below are examples of how to assign values to variables in C:
1. Declaration and Initialization
You can declare a variable and assign a value to it at the same time.
int a = 10; // Integer variable initialized to 10
float b = 3.14; // Float variable initialized to 3.14
char c = 'A'; // Char variable initialized to 'A'
2. Separate Declaration and Assignment
You can declare a variable first and assign a value to it later.
int x; // Declare an integer variable
x = 20; // Assign value 20 to the variable
3. Assigning Values Using Expressions
Variables can also be assigned values using expressions.
int x = 5;
int y = 10;
int z = x + y; // z is assigned the result of x + y (15)
4. Using Constants
You can use constants for assignment to ensure immutability.
const int MAX_VALUE = 100; // MAX_VALUE cannot be changed later
5. Pointer Assignments
For pointers, you assign memory addresses.
int a = 10;
int *ptr = &a; // ptr is assigned the address of a
6. Compound Assignment Operators
C supports compound assignment operators like +=, -=, *=, etc.
int num = 10;
num += 5; // Equivalent to num = num + 5; num becomes 15
num *= 2; // Equivalent to num = num * 2; num becomes 30
Example: Assigning Values
#include <stdio.h>
int main() {
int x; // Declaration
x = 10; // Assignment
printf("Value of x: %d", x);
return 0;
}
Output
Value of x: 10