Variable Declarations and Data Types
Variable Declarations and Data Types
User-defined Identifiers
- Definition: Names in programming that refer to variables, functions, or other entities.
- User-defined identifiers follow specific rules and conventions:
- Must consist only of letters, digits, and underscores.
- Cannot begin with a digit.
- Cannot be a C reserved word.
- Existing identifiers in the C standard library should not be redefined.
Valid User-defined Identifiers Examples
- Valid examples:
num1, pneumonoultramicroscopicsilicovolcanoconiosis
- Invalid examples:
num 1 (contains a space) ag@in (contains special character) int (reserved word)
- Note: Identifiers are case-sensitive.
Best Practices for Naming Identifiers
- Use meaningful names that convey purpose.
- Follow consistent naming conventions:
- Camel Case (e.g.,
myVariableName) - Snake Case (e.g.,
my_variable_name) - Pascal Case (e.g.,
MyVariableName)
Reserved Words in C
- Definition: Keywords that have special roles within the language.
- Note: IDEs often color these words differently to distinguish them from user-defined identifiers.
- Sample Reserved Words:
auto, extern, signed, break, float, sizeof, case, for, static, char, if, struct, const, inline, switch, continue, int, typedef, default, long, union, do, register, unsigned, double, restrict, void, else, return, volatile, enum, short, while
Understanding Variables
- Definition: A variable is a named memory location capable of holding data of a specified type.
- Characteristics:
- The stored data (value) can change during program execution.
- Visual representation:
- Memory Location structure can be visualized as:
- #E #D #C #B #A
- Memory Content: stack space
Variable Declarations
- Purpose: Informs the compiler of a variable's existence, type, and permissible operations.
- Syntax:
- Single Variable:
type identifier; - Example:
int num;, double average;, char choice; - Multiple Variables:
type identifier1, identifier2; - Example:
int num1, num2;, double average1, average2;
- Important Note: In C, variables must be declared before usage.
Data Types Overview
- Definition: Specify the type of data and its operations while determining memory allocation.
- Fundamental Data Types:
int: Represents integer (whole numbers). double: Represents real numbers with fractional parts. float: Similar to double but with smaller memory requirements; less precision. char: Represents a single character value (ASCII).
- Important Notes:
double has twice the precision of float; avoid using them interchangeably to prevent data loss.- ASCII representation is case-sensitive (e.g., 'A' vs. 'a').
- Characters are enclosed in single quotes such as: 'A', 'a', '8', '?', '\n'.
Escape Sequences
- Meaning of Common Escape Sequences:
\a: Alert \b: Backspace \n: Newline \t: Horizontal Tab \v: Vertical Tab \\: Backslash \': Single Quote - `\