DEV Community

Cover image for Data Types, Variables and Constants in C++
Fatih Küçükkarakurt
Fatih Küçükkarakurt

Posted on • Updated on

Data Types, Variables and Constants in C++

We continue our C++ tutorial series. If you haven't read the introduction, click the link below.

C++ For Beginners


All variables to be used in C++ must be declared and introduced to the program before they are used. During this declaration, the data type of the variable must also be determined.

The basic usage is shown as:

<datatype> <name of variable>;

The basic data types commonly used in C++ are:

They are used to define Integers
<int> |<long>|<short>

The <int> and <long> data types occupy 4 bytes of memory, and the <short> data types occupy 2 bytes.


They are used to define decimal numbers

<double>|<long double>|<float>

The <double> and <long double> data types occupy 8 bytes of memory, while the <float> data types occupy 4 bytes.


They are used to identify an alphabetic character or strings of characters

<char>

Each character occupies 1 byte of memory.


You can review the table below for the data types used in C++.

img1

Declaration of Variable Data Type

To declare the data type of the variable to be used in C++, a definition is made as follows:

<datatype> <name of variable>;

int age;
float price;
char letter;
Enter fullscreen mode Exit fullscreen mode

It is possible to change the content of a variable by assigning a specific value anywhere in the program. Often, however, the data type of the variable is determined from the outset, while it is desirable to have a value as well.

<datatype> <name of variable> = <value>;

int age = 26; 
float price = 32.95; 
char letter = 'f'; 
Enter fullscreen mode Exit fullscreen mode

If we are going to use more than one variable in our program, we can define these variables by writing them side by side, provided that they are of the same type.

int num1, num2; 
int num1=13, num2=14; 
Enter fullscreen mode Exit fullscreen mode

Lines where the variable data type is declared, of course, again ";" must end with.

Code:

#include <iostream>
using namespace std;

int main() 
{
   int smallest=10; 
   int largest=100; 

   cout <<"Smallest Number: " << smallest << "\n"; 
   cout <<"Largest Number: " << largest << "\n";
   return 0; 
}
Enter fullscreen mode Exit fullscreen mode

Output:

Smallest Number: 10
Largest Number: 100
Enter fullscreen mode Exit fullscreen mode

Variable Naming Conventions

There are some important rules to consider when defining a variable name in C++.

  • C++ is case sensitive. e.g;
char letter; 
char Letter; 
char LETTER;
Enter fullscreen mode Exit fullscreen mode

All three of the above statements describe different variables. Therefore, we must be very careful when using lowercase and uppercase letters in variable names.

  • No symbols should be used in variable names, except for the numbers, lowercase alphabetic characters, and uppercase alphabetic characters in the table above. However, the underscore (_) character is excluded from this scope and can be used in variable names.

  • Variable names must begin with a letter or an underscore (_) character, never with a number, symbol, or symbol.

int num;
int _num;  
Enter fullscreen mode Exit fullscreen mode
  • The name of a variable can be up to 255 characters.

  • Space characters should not be used in variable names. However, the underscore (_) character can be used instead of a space.

int summer_of_sixtynine;

  • C++-specific keywords cannot be used in variable names. These words are given in the table below:

img2

Variables

Variable definitions can be made for different purposes in C++. Although various types of variables are used in C++ programs, for now we will consider 2 types of variables that are frequently used.

Local Variables:

If there is more than one function in the program, it is the type of variable that can only be valid in the function it is defined in. Such variables must be enclosed in { } signs that indicate function boundaries.

Global Variables:

It is the variable type that can be valid in all functions in the program. Such variables must be placed outside of the { } signs that specify function boundaries.

Static Variables:

When a locally defined variable in a function is required to remain constant and not change if the function is called repeatedly as long as the program is running, that variable should be defined as a static variable.

Constants

Constants are program components whose value does not change from the beginning to the end of the program. Constants with the following data types can be used in C++:

  • Integer Constants
  • Decimal Constants
  • Character Constants
  • String Constants

Integer Constants

There are three types: 'int' (integer), 'short' (short integer) and 'long' (long integer). Let's take 1995 as an example and explain the job of defining the type of an integer in this example.

To indicate which type a constant belongs to, a character is added to the end of that constant to indicate its type. If a numeric expression does not have any characters at the end, the type of that expression is 'int'. In this case, the expression 1995 in our example is an integer of type 'int'. To designate this expression as type 'long' we need to append 'l' or 'L' character:

1995l or 1995L. That way the expression now belongs to type 'long' and not type 'int' an example and explain the job of defining the type of an integer in this example.

Also, integers that cross the 'int' type limits in the flow of the program are automatically converted to 'long', even if they do not have a trailing 'l' or 'L' suffix.

There is a special case for the 'short' type. When calculating the value of an expression, it is treated like 'int' even though it belongs to type 'short'. In this case, we can say that there is no constant of type 'short'. Because constants within the bounds of 'short' are considered as type 'int' by C++.

Floating Constants

There are three types: 'float' (floating decimal), 'double' (double decimal) and 'long double' (long decimal). Let's take the expression 1881.1938 as an example and explain the job of defining the type of an integer in this example.

If a decimal constant does not have any characters at the end, the type of that expression is considered 'double'. In this case, 1881.1938 in our example is a decimal constant of type 'double'. To designate this expression as a type 'float' we need to append the 'f' or 'F' character: 1881.1938f or 1881.1938F. This way the expression no longer belongs to the 'double' type but of the 'float' type.

Although not often used, to specify a decimal constant of type 'long double', we must append the character 'l' or 'L': 1881.1938l or 1881.1938L.

Character Constants

We know that type 'char' takes a value between -128 and +127 or 0 and +255. Well, since these constants are named 'characters' and have an alphabetic nature, why are we still talking about numerical expressions?

Because every character used in C++ has a numeric equivalent in the **ASCII (American Standard Code for Information Interchange) **table, and these numbers, in which the character constants are kept within the specified ranges, are the ASCII equivalents of the characters used. In other words; When we talk about 97 as the character constant, we are actually talking about the character 'a', which is the ASCII table equivalent of 97.

When using character constants, we can use the numeric equivalents of the characters. Of course, the commonly preferred usage in C++ is to use the characters themselves. However, when we are going to use the characters themselves, we must enclose these characters in single quotes (').

In the following lines, two variables of type char are defined and the constants 103 and 'g' are assigned to these variables, respectively.

char character1=103; 
char character2='g'; 
Enter fullscreen mode Exit fullscreen mode

Since the numeric equivalent of the 'g' character in the ASCII table is 103, these two lines actually mean the same thing. However, pay special attention to the fact that the 'g' character is written in single quotation marks.

String Constants

'string' (character) literals consist of sequentially ordered strings of character literals. In C++, every expression enclosed in double quotes (") is a constant of type 'string'. Consider the following examples:

“Fatih" "1995" "1920.1923" "Harvard University"

As you can see, numeric expressions enclosed in double quotes are now a 'string' constant. We can no longer do numerical operations such as addition and subtraction with them.

Actually there is no type named 'string' in C++. The 'string' type occurs when the compiler treats multiple character constants as a string of characters. Accordingly, the expression "Fatih" would actually work like this:

'F' 'a' 't' 'i' 'h'

The compiler treats all these characters as a string and puts them together by adding the '\0' character to the end.

Constants are defined with the word const in the C++ program, and the following definitions are made to declare the data type of the invariant to be used:

int const constant name = value;
char const constant name = 'value';
Enter fullscreen mode Exit fullscreen mode

Code:

#include <iostream>
using namespace std;

int const age = 15;
char const gender = 'M';

int main() 
{
   cout << " Age: " << age <<"\n";
   cout << " Gender: " << gender <<"\n";

   return 0; 
} 
Enter fullscreen mode Exit fullscreen mode

Output:

Age: 15
Gender: M
Enter fullscreen mode Exit fullscreen mode

Type Conversion

Variables or constants in our programs can be of different types. If this is the case, it is important what type of calculation result will be in our mathematical operations. Therefore, type conversion must be done to avoid an error.

Code:

#include <iostream>
using namespace std;

int main(){

  int num=9; 
  float a,b,c; 

  a=num/4; 
  b=num/4.0; 
  c=(float)num/4; 

  cout << "a value= " << a << endl; 
  cout << "b value= " << b << endl; 
  cout << "c value= " << c << endl; 

return 0; 
}
Enter fullscreen mode Exit fullscreen mode

Output:

a value= 2
b value= 2.25
c value= 2.25
Enter fullscreen mode Exit fullscreen mode

In the above application:

In the first operation, we divide the variable named <num> by an integer value; The decimal point is ignored and the result is assigned to variable <a> as an integer.

In the second operation, we divide the variable named <num>, which is an integer, by a decimal value; The part after the comma is taken into account and the result is assigned to the variable <b> as a decimal value.

In the third operation, we first convert the variable named <num>, which is an integer, into a variable of type <float>. Next, we divide the variable that is now <float> by an integer value; the result is assigned as a decimal value to the variable <c>.

Summary

If you've come this far, congratulations. You are now familiar with the data types, constants, and variables of the C++ programming language. C++ is a language with so many features to explore. So never forget to learn, wonder and research.

It is a difficult language as well as a fun one. But if you enjoy it, C++ will give you more.

Top comments (14)

Collapse
 
pauljlucas profile image
Paul J. Lucas

The and data types occupy 4 bytes of memory, and the data types occupy 2 bytes.

No. The standard guarantees only minimum sizes. It also only says that sizeof(short) <= sizeof(int) <= sizeof(long). You also left out long long.

They are used to define decimal numbers

No. They're used to defined floating point numbers. A "decimal number" is a representation of a number in base 10.

They are used to identify an alphabetic character or strings of characters

No. char is used to define only a single character. A "string of characters" is represented by an array of char. You also left out wchar_t.

Each character occupies 1 byte of memory.

No. By definition, sizeof(char) is always 1, but that number has nothing to do with how many physical bytes of memory it occupies.

char letter = "f";

This is wrong. It needs to be 'f' in single quotes in order to be a char.

C++-specific keywords cannot be used in variable names.

No. They can't be used as names of anything (not only variables). However, they can be used in variable names, e.g., character is a perfectly valid name even though char is in character.

[Global] variables must be placed outside of the { } signs that specify function boundaries.

No. This is still a global variable, yet it is inside {}:

namespace { int x; }
Enter fullscreen mode Exit fullscreen mode

I would suggest that you don't use {} as part of your explanation.

The compiler treats all these characters as a string and puts them together by adding the '/0' character to the end.

No. It's \0.

Collapse
 
fkkarakurt profile image
Fatih Küçükkarakurt

First of all, thank you for your comment.

1- In your first comment, you commented "No" to the subject you mentioned. What is wrong, I do not understand. Doesn't int and long take up 4 bytes and short 2 bytes? We can even say 8 bytes for long. 4 Byte was for 32-bit operating systems. You also mentioned the long long structure. Here I am preparing a beginner level article. How many times do we use 64 bytes of data at the beginner level?

2- In your second comment, you mentioned decimals. No, your answer is quite ironic. Isn't every number we use used in modular arithmetic 10? Decimal numbers actually mean base 10 numbers anyway.

3- Let's come to your third comment. char is not used for just a single letter. Haven't you seen a usage like char str[4] = "C++" before? So when using char, we can also use character strings.

4- In your fourth comment, we are actually talking about the same thing. Each character of the number you entered will occupy a certain amount of memory. But each unit actually occupies 1 byte of space.

5- You're right about the double quotes here. Habit from different software languages. Let's also tell our friends here that single quotes should be used in single characters. I'm editing this part and thank you for your attention.

6- When writing character, you are not using char anyway. What we're talking about here is just using 'char' or not. To give an example from daily life, there is quite a big difference between the number 10 and the number 1050. We are not breaking the rule just because we used 10 when writing 1050.

7-

#include  <iostream>
using  namespace std;
// Global variable declaration:
int g;  
int main ()  { //I'm talking about the {} signs here
    // Local variable declaration:  
    int a, b; 
    a =  10; 
    b =  20; 
    g = a + b; 
    cout << g;  
    return  0;
}
Enter fullscreen mode Exit fullscreen mode

Also aren't you going to write any function inside the namespace? As I stated in the text, I am describing the area outside the {} signs of the Function.

8- Yes /0 is an incorrect usage. My fault. Thank you. I am editing.

Collapse
 
pauljlucas profile image
Paul J. Lucas

Doesn't int and long take up 4 bytes and short 2 bytes?

No. See here and the sentence that begins with "Besides the minimal bit counts, the C++ Standard guarantees that ...."

Isn't every number we use used in modular arithmetic 10?

No. I can use any base I like. C++ directly supports octal (base 8) and hexadecimal (base 16) also.

Decimal numbers actually mean base 10 numbers anyway.

Yes, I know; but that has nothing to do with floating point numbers.

char is not used for just a single letter.

Yes, it is.

Haven't you seen a usage like char str[4] = "C++" before?

Yes, and that is not a char. That's an array of char. They are not the same thing.

But each unit actually occupies 1 byte of space.

Your original comment is true only if you restrict your character set to an 7 or 8 bit character set, such as ASCII or EBCIDIC. Other character sets such as Unicode when represented as UTF-16 occupies 2 bytes per character, UTF-32 occupies 4 bytes per character, or UTF-8 occupies 1-to-4 bytes per character. You can't really get away with ignoring Unicode these days.

Thread Thread
 
fkkarakurt profile image
Fatih Küçükkarakurt

No. See here and the sentence that begins with "Besides the minimal bit counts, the C++ Standard guarantees that ...."

The guarantee does not mean that they do not take up 4 and 2 bytes of space. There is nothing wrong with my sentence.

No. I can use any base I like. C++ directly supports octal (base 8) and hexadecimal (base 16) also.

Of course, you can use whatever base you want. But the base we use by default is 10. I did not say that C++ does not support other bases. You can easily do simple modular arithmetic in almost any language. So, in fact, there is nothing wrong with this sentence.

Yes, I know; but that has nothing to do with floating point numbers.

Don't we define decimals with floats? Now that I've said that, you're going to say, "No, I can use a double". Please see this answer by Duthomhas in 2010. I'm sure you and I are talking about the same thing.

Yes, and that is not a char. That's an array of char. They are not the same thing.

This does not indicate that it is not a char. String, letter, word etc. inside char. We can fit a lot of things. It should not be thought of as it is written in the books.

Your original comment is true only if you restrict your character set to an 7 or 8 bit character set, such as ASCII or EBCIDIC. Other character sets such as Unicode when represented as UTF-16 occupies 2 bytes per character, UTF-32 occupies 4 bytes per character, or UTF-8 occupies 1-to-4 bytes per character. You can't really get away with ignoring Unicode these days.

You know that being able to generalize and explain things in the simplest way in science and software is a very, very difficult task. If we try to explain all these details and exceptions, it would take a few months to write an article, right? After all, we are talking about languages like C/C++. It's very nice of you to add to the comments and point out some typos. Thank you for this. But you shouldn't call false statements all of them. Because it's true. By saying that you are wrong, you are trying to express that what I wrote is completely wrong and false. I guess it's a software developer disease. "Oh wait, there is actually a situation like this and this expression can also be used like this." I would be much happier if you left a comment like this. Style is an important thing.

But thank you very much for your interest and attitude. We have a lot to learn from you. After all, you are more experienced.

Thread Thread
 
fkkarakurt profile image
Fatih Küçükkarakurt

Also yes I have read them all and I want to say "purple" to you. 😄

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

The guarantee does not mean that they do not take up 4 and 2 bytes of space.

On your particular machine, they take up that amount of space. That is not universally true.

There is nothing wrong with my sentence.

It's simply not true and repeatedly saying it is doesn't make it so.

Don't we define decimals with floats?

No, you define floating-point numbers with float, double, or long double. You are still confusing the concepts of "bases" with "integer" vs "floating-point." "Floading-point" is its own concept. Your original section title was "Decimal constants"; it should have been "Floating-point constants." This:

int x = 42; // This is also a decimal!
Enter fullscreen mode Exit fullscreen mode

is decimal number. Just because it also happens to have no fractional part doesn't make it not a decimal.

This does not indicate that it is not a char.

Types and arrays of types simply aren't the same thing. Again, repeating otherwise doesn't make it true.

You know that being able to generalize and explain things in the simplest way in science and software is a very, very difficult task.

Yes, but that doesn't mean you state things as fact when they're not. If you initially want to make a simplified statement, you put something like either a parenthetical comment or footnote that explains that it's not strictly true following by a "more later" where you will eventually explain the details. For example, you wrote:

Each character occupies 1 byte of memory.

I would have written:

C++ inherits its primitive types from C. Back when C was invented in 1978, characters (individual letters, numbers, or symbols) were very western-alphabet-centric and so the char type (inherited from C) is only big enough to store a single character from a western alphabet. Today with software being used all over the world by many people who don't use western alphabets, char is woefully inadequate; but for now, we'll make the simplifying assumption that it stores a single character.

Thread Thread
 
fkkarakurt profile image
Fatih Küçükkarakurt

On your particular machine, they take up that amount of space. That is not universally true.

Please write a C++ textbook that you can fully generalize universally. I promise I will buy first.

And yes there is nothing wrong with my sentence. You know this is true. It would take a lot of time to write separate information for 32-bit operating systems or IBM quantum computers, wouldn't it? What you're talking about is "Hey, you know, there are actually some exceptions, for example...". But no, you think it's all wrong. No, everything is not wrong.

No, you define floating-point numbers with float, double, or long double. You are still confusing the concepts of "bases" with "integer" vs "floating-point." "Floading-point" is its own concept. Your original section title was "Decimal constants"; it should have been "Floating-point constants." This:

I already explained float, double, or long double above. Also, I wish you had a look at the link I posted. Of course, I know that 14 and 14.0 are decimal numbers and they are equal to each other. It's pretty easy to break the rules of a programming language. we can print numbers from 1 to 100 without using any loops. So, when describing cycles, "are we going to say you don't need this anyway?".

Types and arrays of types simply aren't the same thing. Again, repeating otherwise doesn't make it true.

Ok, I already said above that "char is used for characters and strings." what is wrong with this sentence? With char we can do it in a list, we can do it in an array, we can also define just one letter. I'll tell you about Arrays and Pointers anyway.

C++ inherits its primitive types from C. Back when C was invented in 1978, characters (individual letters, numbers, or symbols) were very western-alphabet-centric and so the char type (inherited from C) is only big enough to store a single character from a western alphabet. Today with software being used all over the world by many people who don't use western alphabets, char is woefully inadequate; but for now, we'll make the simplifying assumption that it stores a single character.

If you had read the first article, you would know that we act on the basis of ASCII.

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

Of course, I know that 14 and 14.0 are decimal numbers and they are equal to each other.

Then I really don't know why you persist in defending the position that your section title of "Decimal numbers" is correct.

It's pretty easy to break the rules of a programming language. we can print numbers from 1 to 100 without using any loops. So, when describing cycles, "are we going to say you don't need this anyway?".

I really can't follow this; nor do I see what it has to do with the fact that floating-point numbers are correctly called "floating-point numbers" and not "decimal numbers." Really, all you have to do is change the one word of "decimal" to "floating-point" and then your section would be correct. I really don't understand why you are staunchly defending the incorrect term.

If you had read the first article, you would know that we act on the basis of ASCII.

If you're writing for a web audience, you have to expect that people will read things out of order. If you explained earlier what I did, then in this post, you should have put a reminder, perhaps with a link, back the original explanatory text.

Thread Thread
 
pauljlucas profile image
Paul J. Lucas • Edited

By the way:

Please write a C++ textbook that you can fully generalize universally. I promise I will buy first.

There's no need. There are already many excellent C++ textbooks and web sites out there. I don't see the point in writing something that's already done well elsewhere. So I really don't understand the entire purpose of your posts. Even if your posts were 100% correct, what new unique perspective are your posts bringing to the table?

Thread Thread
 
fkkarakurt profile image
Fatih Küçükkarakurt

You may be right about the title. This looks misleading. Thanks.

There's no need. There are already many excellent C++ textbooks and web sites out there. I don't see the point in writing something that's already done well elsewhere. So I really don't understand the entire purpose of your posts. Even if your posts were 100% correct, what new unique perspective are your posts bringing to the table?

Many people are here to learn, to be persistent and to share something. What is not new to you may be new to someone else.

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

Many people are here to learn, to be persistent and to share something. What is not new to you may be new to someone else.

Then write a post recommending an already-written good C++ book; or link to an already-written C++ web series that you've found. Writing yet another series of intro to C++ posts seems like a lot more work when excellent alternatives already exist.

Thread Thread
 
fkkarakurt profile image
Fatih Küçükkarakurt

Thank you. And I hope you didn't think I was taking a harsh stance. I want you to know that I will benefit from your experience. I've already started reviewing most of your projects in your Github Repo.

Thread Thread
 
pgradot profile image
Pierre Gradot • Edited

Decimal vs floatting-point : en.wikipedia.org/wiki/Decimal

The decimal numeral system (also called the base-ten positional numeral system, and occasionally called denary /ˈdiːnəri/[1] or decanary) is the standard system for denoting integer and non-integer numbers.

en.wikipedia.org/wiki/Floating-poi...

In computing, floating-point arithmetic (FP) is arithmetic using formulaic representation of real numbers as an approximation to support a trade-off between range and precision.

Can we say that 3.14 is a decimal number and that in the expression float a = 3.14 uses a decimal number to initialize a floatting-point variable?


About sizes of integral types:

The <int> and <long> data types occupy 4 bytes of memory, and the <short> data types occupy 2 bytes.

This is true on most modern computers, with the most common toolchains. This is not guaranteed in C++ for every CPU with every toolchain. See stackoverflow.com/questions/589575... for more details.

Thread Thread
 
pauljlucas profile image
Paul J. Lucas

There's a distinction between the numeric value and how that value is expressed or printed. 3.14 is a floating-point number printed in a base 10, that is using decimal digits. However, the same floating point number can also be printed in any arbitrary base, e.g., base 2 (using binary digits), base 8 (using octal digits), or base 16 (using hexadecimal digits). For example, see here. Not that neither C nor C++ supports any "point" other than a decimal point, but that doesn't invalidate the concepts.