Data Types and Variables in C

Data Types and Variables in C

Rishabh Kumar
·Jan 26, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

Variable

A variable is an alias for the memory location. We can store and change its data any number of times.

Video Explaination

Syntax

type (variables separated by comma);

Example

int a,b,c;

Initialisation

a = 5;

we can also initialise variables while declaration

int a = 5, b = 10;

Rules for defining alias or variable

  • Allowed character, alphabets, digits and underscore(_)
  • Cannot start with a number
  • Can't use reserved keywords or whitespaces

Valid Examples

int rish;
int rish123;
int rish_567;
int _rish_code

Invalid Examples

int @hey;
int 5rish;
int int;
int rish code;

Types of variables

Local Variable (Declared inside block)

#include <stdio.h>
int main()
{
    int a = 10; //local variable
    return 0;
}

Global Variable (Declared outside block)

#include <stdio.h>
int y = 20; // global variable
int main()
{
    int a = 10; //local variable
    return 0;
}

Static Variable (Retains it's value between multiple function calls)

#include <stdio.h>
void function1();
int y = 20; // global variable
int main()
{
    int a = 10; //local variable
    function1();
    function1();
    function1();
    function1();
    function1();
    function1();
    return 0;
}
void function1()
{
    int x = 10;        //local variable
    static int y = 10; //static variable
    x = x + 1;
    y = y + 1;
    printf("\n%d,%d", x, y);
}

// output 
PS C:\Users\risha\Desktop\c> gcc .\hello.c
PS C:\Users\risha\Desktop\c> .\a.exe

11,11
11,12
11,13
11,14
11,15
11,16
PS C:\Users\risha\Desktop\c>

Automatic Variable (all variables are automatic variable. Explicit declare ex auto int y = 20)

#include <stdio.h>
int main()
{
    int x = 10;      //local variable (also automatic)
    auto int y = 20; //automatic variable
    return 0;
}

External Variable (can be used in other file)

#include <stdio.h>
extern int x = 10; //external variable (also global)
int main()
{
    return 0;
}

Data Types

  • Primary data type: int, char, float, double
  • Derived Data Type: array, pointer, structure, union
  • Enumeration data type: enum
  • Void Data Type: void

Data Type.png

Sample Code

#include <stdio.h>
int main()
{
    int a = 1;
    char b = 'C';
    double c = 7.77;
    // print variable explain comments
    printf("%d\n", a);
    printf("%c\n", b);
    printf("%.2lf\n", c);
    return 0;
}

Did you find this article valuable?

Support Rishabh Kumar by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this