What is the difference between literal and constant in C++?

C++ProgrammingObject Oriented Programming

A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals.

A constant is a data type that substitutes a literal. Constants are used when a specific, unchanging value is used various times during the program. For example, if you have a constant named PI that you'll be using at various places in your program to find the area, circumference, etc of a circle, this is a constant as you'll be reusing its value. But when you'll be declaring it as −

const float PI = 3.141;

The 3.141 is a literal that you're using. It doesn't have any memory address of its own and just sits in the source code.

Published on 16-Feb-2018 13:59:53