4(a): ***(Syntax)*** Constants, Variables and Keywords

Keywords:
Keywords are reserved words whose meaning is already known to the compiler and they can not be used elsewhere in the program for naming a variable or a function.
==> List of C++ keywords is: https://en.cppreference.com/w/cpp/keyword
Constants:
Constants are very similar to a variable and they can also be of any data type. The only difference between a constant and a variable is that a constant’s value never changes.
Types of constants:
There are three types of constants:
- Integer Constants ===================> -1, 6, 7, 9 (all non-fraction numbers)
- Real Constants =====================> -30.1, 2.5, 7.0 (all fraction numbers)
- Character Constants =================> 'a' '$' '@' '+' (letters or characters enclosed within single inverted commas)
String Laterals (String Constants):
They are a sequence of characters enclosed in double quotation marks(" "). For example, “This is a string literal!” is a string literal or just string. Escape sequences are also string literals.
If you write const before a variable, it will become constant for rest of the program and changing it will cause error.
#include <iostream>
using namespace std;
int main()
{
const float PI = 3.14; //PI becomes constant
cout << "The value of PI is " << PI << endl;
PI = 3.00; //error, since changing a const variable is not allowed.
}
Thus output will be:
error: assignment of read-only variable 'PI'
C++ Variables:
Variables are containers for storing data values. For example:
a = 3; // a is assigned "3"
b = 4.7; // b is assigned "4.7"
c = 'A' ; // c is assigned 'A'
Rules for naming a Variable:
- A variable name can only contain alphabets, digits, and underscores( _ ).
- No commas, blanks, or special characters other than underscore ( _ ) are allowed.
- Variable names are case-sensitive ie Abc and abc are two different variables.
We must create meaningful variable names in our programs. This increases the readability of our program.
Types of Variables:
Various types of integers and their writing format in C are as follow:
- Integer variables ======> int a = 3; numbers without decimal
- Real variables ========> float a = 7.7;
int a=7.7;is wrong decimal number of low precision - Character variable ====> char a = 'B'; add '' single character i.e '+' or 'A'
- Double variable =======> double a = 3.1412653589 decimal number of high precision
- Boolean variable ======> bool a = true store true or false, 0 or 1
- String variable ========> string a = "This is my name"
Declaration of Variable:
We cannot declare a variable without specifying its data type. The data type of a variable depends on what we want to store in the variable and how much space we want it to hold. The syntax for declaring a variable is simple:
data_type variable_name = value;
For example:
int a=3;
float b=4.5;
char c='A';
double d=3.14159265;
bool e=true;
Comments
Post a Comment