Creating Variables in C

Variables are fundamental to programming in C. They act as storage locations in memory with a specific data type, where you can store and manipulate data.

Key Topics

1. Variable Declaration

Before using a variable in C, you must declare it by specifying its data type and name.

Example: Declaring Variables

int age;
float salary;
char grade;

Code Explanation: Here, int, float, and char are data types. Variables age, salary, and grade are declared but not initialized with values.

2. Variable Initialization

Variable initialization assigns an initial value to a variable at the time of declaration.

Example: Initializing Variables

int age = 25;
float salary = 50000.00;
char grade = 'A';

Code Explanation: Variables are declared and initialized simultaneously. age is set to 25, salary to 50000.00, and grade to 'A'.

3. Common Data Types

C offers several built-in data types. Here are some common ones:

Data Type Description Example
intInteger numbersint count = 100;
floatFloating-point numbersfloat price = 9.99;
doubleDouble-precision floating-point numbersdouble pi = 3.14159;
charSingle characterschar letter = 'A';

Best Practices

  • Always initialize variables before use.
  • Choose appropriate data types to optimize memory usage.
  • Use meaningful variable names for better readability.

Don'ts

  • Don't use uninitialized variables; it leads to undefined behavior.
  • Don't use keywords as variable names.
  • Don't ignore the range limits of data types.

Key Takeaways

  • Variables store data and must be declared with a data type.
  • Initialization assigns an initial value to a variable.
  • Choosing the correct data type is crucial for program efficiency.