What is difference between followin intialization.int iVar1;int iVar2 = int();and which one of two should we prefer always and why?

Questions by mohit12379   answers by mohit12379

Showing Answers 1 - 7 of 7 Answers

in first case a variable will be create in memeory with the default base type value (depending upon compiler 2 compiler) bcoz it is not initialized. in second case the variable will be created in the memory with the value retuned by the function int() (if int is a user define function) the second statement should have been int *i = new int();

  Was this answer useful?  Yes

@PRITI YADAV HAV U TRIED THE FOLOWING STATEMENT EVER

   int iVar2 = int();

PLS TRY IT....

FOR UR KIND INFO :- int * ivar2 = new int(); and int iVar2 = int(); are two different statement... thas why i have asked this que...., DNT MIX IT.


  Was this answer useful?  Yes

ramachandra

  • Sep 13th, 2006
 

Preeti Yadav is right, Ivar1 is not initialized but in the second case compiler initilizes the Ivar2 to sero. create a console program and use "COUT" to print Ivar1 and Ivar2 and observe that Ivar1 prints junk value and Ivar2 value will be zero

  Was this answer useful?  Yes

Shiva Shankar Anumula

  • Oct 15th, 2006
 


int iVar1;
int iVar2 = int();

In first case, memory fpr iVar1 is allocated and it is not intialized.

 second case is used to intialize the '0' to ivar2

  Was this answer useful?  Yes

Ashish

  • Nov 7th, 2006
 

int iVar1 does not initalize the iVar1. Its C style of declation of integer.

whereas in C++ everything is implemented using classes, even basic built-in data types.

int iVar2 = int();

so int() is nothing but constructor that creates one object of int type and assigned to iVar2. (means assignment operator is overloaded). try int(5)... i.e.

int iVar2 = int(5);

in this case iVar2 is initalized to 5.

  Was this answer useful?  Yes

Anil

  • May 21st, 2007
 

depends

if use in main both will get initialize to '0'.
ie: global

if use inside a function (local) iVar1 will be garbage, iVar2 will be initialised to '0';

  Was this answer useful?  Yes

mucdull

  • Nov 17th, 2008
 

int   iVar1;   // iVar1 is never initialized
int   iVar2 = int();   // iVar2 will always be initialized with some initial value

The latter should be used because use of uninitialized variable is dangerous and can cause runtime check failure for some C++ compiler.


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions