C - Introduction Initializing Variables

Introduction

In the previous example, you declared each variable with a statement such as this:

int cats;    // The number of cats as pets

You set the value of the variable cats using this statement:

cats = 2;

This sets the value of cats to 2.

The first statement creates the variable called cats, but its value will be whatever was in memory.

The assignment statement that appeared later sets the value to 2.

You can initialize the variable when you declare it.

int cats = 2;

This statement declares cats as type int and sets its initial value to 2.

Demo

// Simple calculations
#include <stdio.h>

int main(void)
{
      int total;//from   w  w w . j  a  v a 2s  .c o  m
      int cats = 2;
      int dogs = 1;
      int bugs = 1;
      int others = 5;
      // Calculate the total number of pets
      total = cats + dogs + bugs + others;

      printf("We have %d pets in total\n", total);   // Output the result
      return 0;
}

Result

Related Topic