Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When declaring a variable in C++/C

Tags:

c++

When I declare a variable, such as:

 int x = 6;

What exactly is x? an address in the memory is usually hexadecimal..
Also, when I'm calling X

x = 2;

How does the compiler know where x is? x isn't an address.

That was my first question.

Second:
Let's say i have an object:
Person p;
p has 2 datamembers:

 int type1, int type2;

What exactly is p, and why do I need to go to p, then the variable?

p.type1, p->type1.
like image 373
user1725859 Avatar asked Oct 12 '12 14:10

user1725859


People also ask

How do you declare a variable in C?

type variableName = value; Where type is one of C types (such as int ), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign a value to the variable.

Which is valid declaration of variable in C?

In C language, a variable name can consists of letters, digits and underscore i.e. _ . But a variable name has to start with either letter or underscore. It can't start with a digit. So valid variables are var_9 and _ from the above question.

When we declare an integer variable in C how much memory is given by system to it?

When we create a variable in a C program, the C compiler allocates a storage space, depending upon the datatype of the variable(8 bits for char , 16/32 bits for int , etc.), and then that storage space is given a name which is the variable name.


2 Answers

In the case int x = 6, x is just a name to help you write the code and the compiler compile it. It's basically an alias for some place in memory, so that it's easier to access it later via x = 2 - this tells both you and the compiler that you want to write the value 2 in that same place.

Same as before, but it takes up more space (sizeof(Person) to be exact). p->type1 is only valid if p is a pointer to a Person (or if you overloaded the -> operator, but it's not the case), p.type1 is the syntax used for an object, to specify which part of the it you want to access.

like image 186
Luchian Grigore Avatar answered Sep 21 '22 19:09

Luchian Grigore


int x=6 ;

Here x is identifier i.e. the name given to memory area where value 6 is stored.
x is simple name just to identify memory area where value 6 is stored.
when u declares variable, that time compiler stores ur variable name in the identifier table.

For person p, here once again p is name given to the memory area,which stores two data member type1 & type2

For accessing the value of type1 & type2, first u have to find the memory area, where they are stored. That's why u have to first access the memory area p & then u can access type1 * type2

like image 26
Ravindra Bagale Avatar answered Sep 19 '22 19:09

Ravindra Bagale