Cpp - Introduction Variable Definition

Introduction

A variable is defined in C++ by stating its type, the variable name, and a semi-colon to end the statement:

int my_int; 

More than one variable can be defined in the same statement as long as they share the same type.

The names of the variables should be separated by commas:

unsigned int my_int, playerScore; 
long area, width, length; 

The my_int and playerScore variables both are unsigned integers.

The second statement creates three long integers: area, width, and length. Because these integers share the same type, they can be created in one statement.

A variable name can be any combination of uppercase and lowercase letters, numbers, and underscore characters _ without any spaces.

C++ is case sensitive, so the my_int variable differs from ones named my_Int or my_INT.

Assigning Values to Variables

A variable is assigned a value using the = operator, which is called the assignment operator.

The?following statements show it in action to create an integer named my_int with the value 13,000:

unsigned int my_int; 
my_int = 13000; 

A variable can be assigned an initial value when it is created:

unsigned int my_int = 13000; 

This is called initializing the variable.

The following code uses variables and assignments to compute the area of a rectangle and display the result.

Demo

#include <iostream> 
 
int main() /*from w  w w  .j a  v  a2  s  .co  m*/
{ 
    // set up width and length 
    unsigned short width = 26, length; 
    length = 40; 

    // create an unsigned short initialized with the 
    // result of multiplying width by length 
    unsigned short area = width * length; 

    std::cout << "Width: " << width << "\n"; 
    std::cout << "Length: "  << length << "\n"; 
    std::cout << "Area: " << area << "\n"; 
    return 0; 
}

Result

Related Topic