definition and declaration + initializing

Feb 19, 2015 at 7:01am
I thought i understand this but I started to get confused by one question in the book
"Why is it a good idea to initialize variables as they are declared?"

At 1st i was like - c'mon its easy, but than i started to think - wait a minute isnt declaration of variable mean
extern int x;, its like void print_hello();

Both are declarations but i thought that we are not assigning anything to declarations but just tell the compiler that there is going to be this variable or function inside the code somewhere. Only later on when we are defining variable or function we give details about functions body or variables value.

I got more confused when one guy in other forums gave example about definitions and declarations and gave the same example

declaration: int x; // i feel like this cant be right coz as i understand here we are actually instantly giving memory block for this variable and i cant type int x; int x; (could type extern int x; extern int x)
definition: int x; //this i agree is definition without initialization

So can we actually "initialize variables as they are declared"?(extern int x = 2;)



Last edited on Feb 19, 2015 at 7:02am
Feb 19, 2015 at 8:57am
You are correct. We initialize variables when they are defined. I don't think the quote is wrong though, only imprecise, because a definition is also declaration.
Last edited on Feb 19, 2015 at 9:03am
Feb 19, 2015 at 11:12am
Thanks a lot for answer :)
Topic archived. No new replies allowed.