Wednesday, 5 February 2025

Variables in C Language

Variables in C Language

Definition:

A variable in C is a name given to a memory location that stores data. The value of a variable can change during program execution.

Syntax:

data_type variable_name = value;

Rules for Naming Variables:

1. Can contain letters (A-Z, a-z), digits (0-9), and underscore (_).


2. Must start with a letter or an underscore.


3. Cannot be a C keyword.


4. Case-sensitive (age and Age are different).




---

Types of Variables in C

1. Integer Variable (int)

Stores whole numbers.

Example:


#include <stdio.h>
int main() {
    int a = 10;
    printf("Value of a: %d", a);
    return 0;
}

Output:

Value of a: 10

2. Floating-point Variable (float, double)

Stores decimal numbers.

Example:


#include <stdio.h>
int main() {
    float pi = 3.14;
    double largeValue = 3.1415926535;
    printf("Float: %f\n", pi);
    printf("Double: %lf", largeValue);
    return 0;
}

Output:

Float: 3.140000
Double: 3.141593

3. Character Variable (char)

Stores a single character.

Example:


#include <stdio.h>
int main() {
    char grade = 'A';
    printf("Grade: %c", grade);
    return 0;
}

Output:

Grade: A

4. String Variable (char array)

Stores a sequence of characters.

Example:


#include <stdio.h>
int main() {
    char name[] = "John";
    printf("Name: %s", name);
    return 0;
}

Output:

Name: John

5. Boolean Variable (_Bool) (C99 and later)

Stores 1 (true) or 0 (false).

Example:


#include <stdio.h>
#include <stdbool.h>
int main() {
    bool isCodingFun = 1; // true
    printf("Is coding fun? %d", isCodingFun);
    return 0;
}

Output:

Is coding fun? 1


---

Types of Variable Scope in C

1. Local Variable: Declared inside a function, accessible only within that function.


2. Global Variable: Declared outside all functions, accessible throughout the program.


3. Static Variable: Retains its value between function calls.


4. Extern Variable: Declared in one file but accessible in another file.




---

Example with Local, Global, and Static Variables

#include <stdio.h>

int globalVar = 20; // Global variable

void demoFunction() {
    static int staticVar = 5; // Static variable
    int localVar = 10; // Local variable
    printf("Local: %d, Static: %d, Global: %d\n", localVar, staticVar, globalVar);
    staticVar++;
}

int main() {
    demoFunction();
    demoFunction();
    return 0;
}

Output:

Local: 10, Static: 5, Global: 20
Local: 10, Static: 6, Global: 20


---

Conclusion

Variables store data and can change values.

Different data types store different kinds of values.

Scope determines variable accessibility.

Static variables retain their values across function calls.


No comments:

Post a Comment