Difference between various initializers in C++

Course Queries Syllabus Queries 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Syllabus Queries related to Course Queries. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I've only recently started learning C++ as part of my 10th Grade syllabus, and am only aware of the basics, thus simple answers (if possible) will be appreciated. I'm rather confused between initialization and assignment.

//Case 1
int a=5; //This is initialization
a=6; //This is assignment

From what I've understood, a variable is initialized when you give it a value to hold while declaring it. Changing this later in the code will be an assignment. Right?

What about :

//Case 2
int b;
{
//Block of code which does not call variable b
.
.
.
//End of block
}
b=6; // Is this initialization as well?

While 'b' is uninitialized when we declare, we later assign the value '6'. Can we say the 'b' is initialized now? Or are the terms initialized and uninitialized not applicable to 'b' anymore?

I read the an uninitialized variable holds "garbage values" till it isn't initialized. What exactly are "garbage values"?

What is the difference between the following initializers : '()', '{}', and '='?

profilepic.png
manpreet 2 years ago

 

Okay, once you declare a variable without assigning any value, like

int b; 

that means that the compiler reserves some space in the memory to hold the value (to be exact, in this case the memory is reserved on the stack). But since you didn't assign any value to the variable, it still holds the value, that the assigned space in memory had before. And that can be anything. Those are garbage values.

Initializers:

int b(1);

assigns the value 1 to be (in general, it calls a constructor of the type)

The brackets can be used to initialize arrays like this (edit):

int b[] = {1, 3, 5, 7};

And the = just assigns a value. The difference between this and the first will only become interesting when dealing with more complex types (classes), where you have constructors


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.