DEV Community

Cover image for Data Types and Variables in C
Rishabh Kumar
Rishabh Kumar

Posted on • Originally published at codewithrish.com

Data Types and Variables in C

Variable

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

Syntax

type (variables separated by comma);

Example

int a,b,c;
Enter fullscreen mode Exit fullscreen mode

Initialisation

a = 5;
Enter fullscreen mode Exit fullscreen mode

we can also initialise variables while declaration

int a = 5, b = 10;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Invalid Examples

int @hey;
int 5rish;
int int;
int rish code;
Enter fullscreen mode Exit fullscreen mode

Types of variables

Local Variable (Declared inside block)

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

Global Variable (Declared outside block)

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

Enter fullscreen mode Exit fullscreen mode

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> 
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

External Variable (can be used in other file)

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

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;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)