initializing question?

I was just wondering is it better to initialize all your int, double, float variables before using them for example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

int main( ) 
{
    int first_number = 0,
        second_number = 0;
        
    cout << "Enter first number: ";
    cin >> first_number;
    
    cout << endl;
    
    cin.clear();
    cin.ignore(200, '\n');
    
    cout << "Enter second number: ";
    cin >> second_number;
    
    cout << endl;
    
    cout << first_number << " + " << second_number << " = " << ( first_number +         second_number ) << endl;
    
    system( "pause" );
    return( 0 );
    
}


or its doesn't really matter? Sorry if this question is very basic its just something I wanted to know for a while now?
Opinions vary on this subject, but I think it only matters if the initial value matters.

For example, your program handles user input errors by defaulting to inputs of "0". That is, if the user types EOI [ Ctrl+Z (DOS/Win) or Ctrl+D (Unix) ] when asked to enter the first number, or if he enters something like "no thanks" or any other invalid response, your program:

1. already has a value for first_number (and second_number), that is, it is not changed from zero
2. clears the error flags
3. removes everything bad the user typed (up to and including when he pressed the ENTER key)

In this case, the initial value does matter, because it is used if the user enters invalid input.

+1 also for handling bad input gracefully.
Last edited on
In terms of this program, if you are declaring first_number, and second_number as constants to be set as "0" then you would need to declare them like this:

"const int firstNumber = 0;
const int secondNumber = 0;"

or if you want the user to enter in a value for them that would just be a single number without decimals then you just declare it as an integer:

"int firstNumber;
int secondNumber;"

Also, it is better to use AlphaNumerical characters only in naming varibles, to start a new word simply use a capital letter.

This is what I think you were trying to do, let me know if this is what you we're shooting for.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

int firstNumber;
int secondNumber;
int newNumber;


using namespace std;

int main() 
{

	cout << "Enter first number: " << endl;
	cin >> firstNumber;


	cout << "Enter second number: " << endl;
	cin >> secondNumber;


	newNumber = firstNumber + secondNumber;

	cout << firstNumber << " + " << secondNumber << " = " << newNumber << endl;


	return 0;

}

You are so full of BS that it hurts my eyes.

In terms of this program, if you are declaring first_number, and second_number as constants
You cannot, by definition, assign values to constants. This is useless information anyway, because the OP's question didn't involve const values in any way.

or if you want the user to enter in a value for them that would just be a single number without decimals then you just declare it as an integer
Again, you have missed the mark so far that you are dangerous. Nothing in the OP's post suggests that he does not know this. Convenient how his example actually uses int for his numeric type!

Also, it is better to use AlphaNumerical characters only in naming varibles, to start a new word simply use a capital letter.
I hate studlyCaps and only tolerate them on existing projects. Just who do you think you are declaring all truth in variable naming? You don't know squat.

This is what I think you were trying to do, let me know if this is what you we're shooting for.
QED. His program is superior to yours for the reasons I've already listed in my first response. Try any of the bad inputs I suggested there and your program would crash and burn. Oh, BTW, nice choice of global variables!

Go away.

Sorry to be so harsh, but it really presses my buttons when some newb decides to confuse and ill-inform the OP, especially after I (or someone else) have already thoroughly answered the question.
You cannot, by definition, assign values to constants. This is useless information anyway, because the OP's question didn't involve const values in any way.


he was trying to set first_number and second_number to 0 but not declaring it as const, but then later he asks the user to read in a value to firstnumber

especially after I (or someone else) have already thoroughly answered the question.


I had started typing before there was any response, and didn't see yours until after mine was posted.

I hate studlyCaps and only tolerate them on existing projects. Just who do you think you are declaring all truth in variable naming? You don't know squat.


To be perfectly honest, i used to aswell except like you mentioned almost every project i've came in on has used them and i've grown accustomed to it so I use it as the main way I declare variables.

I was trying to answer his initial question, not any generalities in programming

I was just wondering is it better to initialize all your int, double, float variables before using them for example
You cannot, by definition, assign values to constants. This is useless information anyway, because the OP's question didn't involve const values in any way.

You can assign values to constants, although it's a nasty method. You just need a pointer and a typecast (so the compiler doesn't say "Hey! You can't point that non-const pointer to that constant!")

1
2
3
4
const int myInt = 0;
int* evilPointer = (unsigned int*)&myInt;

*evilPointer = 1;

No constant variables were harmed in the making of this nasty hack.

Anyway...

he was trying to set first_number and second_number to 0 but not declaring it as const, but then later he asks the user to read in a value to firstnumber

If he wants the user to input some values into first_number and second_number, then clearly he doesn't want to use constants. The whole point of constants is that you can be assured that they haven't been changed by some function somewhere along the line (unless that function happens to have been written by me, in which case, indiscriminate and somewhat evil use of pointers may have occurred).



To be perfectly honest, i used to aswell except like you mentioned almost every project i've came in on has used them and i've grown accustomed to it so I use it as the main way I declare variables.

Are you talking about camelCase, or are you referring to the annoying trend of every variable, function, etc. starting with a capital letter? Like this,
int AnnoyinglyNamedFunction()
as apposed to
int lessAnnoyinglyNamedFunction
or like this,
int readbly_named_function()
?

Personally I camelCase variable names and use underscores in unions, structs, functions, etc.

Actually, you know what I just noticed? I use underscores for everything, but camel case in examples. That's weird :l
Last edited on
You can assign values to constants, although it's a nasty method. You just need a pointer and a typecast


There's no guarantee that will work:

1
2
3
4
5
    const int foo = 0;
    int* bar = (int*)(&foo);

    *bar = 1;
    std::cout << foo;  // SURPRISE 


When I compile that in GCC it prints 0. Compiler optimizations and such.
Make it volatile, then. Would that help?
No, it wouldn't.

But anyway, to the original question, here is my opinion.

Computer programming is all about taking some input (an initial state, if you will),
transforming it via a set of steps, and generating some output (a final state, if
you will).

I like for my programs to be in a determinate state from start to finish. Uninitialized
variables are not determinate. Except for extreme circumstances where every ounce
of speed is critical, it seems to me like the extra 1 second of typing to initialize variables
is worth the effort to avoid potential bugs due to using uninitialized variables.

A good habit to get into, however, is to declare variables only at the point where they
are first needed. Said another way, limit the scope of your variables to only that which
is needed. (C programmers are accustomed to declaring variables at the top of the
function or block since C rules require that; in C++, that is not recommended).



A good habit to get into, however, is to declare variables only at the point where they
are first needed.


I generally agree.

But this is a double-edged sword, particularly when loops are concerned.

I'd say that sometimes you're better off declaring complex types ahead of time if there's an upcoming loop to avoid unnecessary ctor/dtor calls (which may result in a lot of unnecessary memory allocation and deleting depending on the type)

Consider the following:

1
2
3
4
5
6
7
8
for(int i = 0; i < 1000; ++i)
{
    /* do a bunch of stuff here */

    std::string foo;

    /* do stuff with foo here */
}


Does it really make sense to run foo's ctor/dtor of foo for every iteration of that loop? I don't think so. In a case like this, I'd put foo outside the loop to avoid that.
There is going to be little difference between

1
2
3
4
5
6
7
std::string foo;
for( int i = 0; i < 1000; ++i )
{
     // stuff
     foo = "bar";
     // more stuff
}


and

1
2
3
4
5
6
for( int i = 0; i < 1000; ++i )
{
     // stuff
     std::string foo = "bar";
     // more stuff
}

.

Why? Think about it. operator=() for string is essentially going to do the same amount
of work as running a destructor followed by a constructor. The destructor deallocates
the buffer, as operator= must do, and the constructor reallocates it, as operator= must
do.
Topic archived. No new replies allowed.