adding integers

when you add numbers, for example
int a=5
int b=6
you also say
int sum = a+b

but why do you need to say int again for sum? it will already be int if it is a+b

is the int for sum not unnecessary?

sorry i am very beginner

In recent versions of C++ (C++11 and later) it is possible to use the auto keyword.

 
auto sum = a + b;

The compiler will deduce the type of sum to be an int because that's the type that it's being initialized with.
Last edited on
C++ is a strongly typed language, each variable must have a type associated with it.

The auto keyword is a fancy thing designed to be helpful for much complicated and advanced things, where it is easier to let the compiler do it, rather than a human making a mistake. In other words it wasn't invented solely because coders didn't want to have to type int again.

One can't omit the variable name sum, because the compiler needs something to associate it's value with. All variables should have a value, that is why it is so important to always initialise the variables with something.
but why do you need to say int again for sum

because sum is a variable and every variable in C++ has to have a type as C++ is (quite) a strongly typed language. In addition to auto, as Peter shows, you could also use decltype:
1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
    int a {5}; //braced initialization / uniform initialization
    int b {6};
    decltype(a+b) sum = a + b;
    std::cout << sum << "\n";
}

But auto is more widely used for variables and decltype for template function return types. There can also be some subtle differences b/w the two sometimes as described below links:
http://stackoverflow.com/questions/12084040/decltype-vs-auto
http://stackoverflow.com/questions/6869888/the-relationship-between-auto-and-decltype
And to add another reason for the type:

You can use other types like float, double, etc. to store the value, hence the compiler needs to know what type you want.

Personally, I don't like the idea that the compiler chooses the type for me...
there are a dozen types of integer as well (many redundant).

say you have this one..

char c = 100;
char b = 100;

d = c+b; //what is d? 200 won't fit into char, the max is 128! int is too big, wastes space. short is about right, but did you want a short? How would it know?

I do not know of any weakly typed languages that have high performance on par with C++. They err on the side of allocating the biggest thing possible which is very inefficient for a number of reasons when your programs become complicated.



Topic archived. No new replies allowed.