Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between -> and . in a struct?

Tags:

c

struct

If I have a struct like

struct account {    int account_number; }; 

Then what's the difference between doing

myAccount.account_number; 

and

myAccount->account_number; 

or isn't there a difference?

If there's no difference, why wouldn't you just use the . notation rather than ->? -> seems so messy.

like image 590
Sam Avatar asked May 13 '11 23:05

Sam


People also ask

What is difference between and -> in C++?

Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow. :: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it.

What is difference between struct and class?

A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit.

What is difference between struct and class in C++?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private. Having imparted this information, I urge you not to exploit it too heavily.

Is a struct a class C++?

Classes and Structs (C++)The two constructs are identical in C++ except that in structs the default accessibility is public, whereas in classes the default is private. Classes and structs are the constructs whereby you define your own types.


2 Answers

-> is a shorthand for (*x).field, where x is a pointer to a variable of type struct account, and field is a field in the struct, such as account_number.

If you have a pointer to a struct, then saying

accountp->account_number; 

is much more concise than

(*accountp).account_number; 
like image 103
rmk Avatar answered Oct 03 '22 01:10

rmk


You use . when you're dealing with variables. You use -> when you are dealing with pointers.

For example:

struct account {    int account_number; }; 

Declare a new variable of type struct account:

struct account s; ... // initializing the variable s.account_number = 1; 

Declare a as a pointer to struct account:

struct account *a; ... // initializing the variable a = &some_account;  // point the pointer to some_account a->account_number = 1; // modifying the value of account_number 

Using a->account_number = 1; is an alternate syntax for (*a).account_number = 1;

I hope this helps.

like image 43
CRM Avatar answered Oct 03 '22 01:10

CRM