Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Asterisks, Ampersand and Star?

Tags:

c++

operators

Recently I came across this video on Programming Paradigms and the prof. used terms like Asterisks, Star, and Ampersand.

This was what how he used those operators:

int i = 37;
float f = *(float*)&i;

And how he voiced line 2 while writing it:

Float "f" equals asterisk float star, ampersand of i

I understand what asterisk and ampersand mean, but what is the significance of using star here? Is it synonymous to asterisk?

like image 606
witherspoon Avatar asked Apr 08 '12 07:04

witherspoon


3 Answers

The * after the float is used to form a type. Very often when referring to a pointer type in words people will say "star" after the type rather "pointer", eg. "malloc returns a void star". I've never heard anyone use "asterisk" to refer to a type.

The * at the start is used to de-reference the pointer thereby accessing the value it points to (interpreted as a float due to the following cast). Again, in my own experience I've never heard anyone use "asterisk" here. People just tend to say "de-reference" to describe the operation being performed.

I wouldn't read too much into it. There are two different contexts here as you rightly spotted and as long as you understand what they mean from a C++ point of view then that's fine.

like image 167
Troubadour Avatar answered Oct 04 '22 23:10

Troubadour


float f = *(float*)&i;

In this case left * and right * has different sematics. Left * means value getting by refernce. Right * declares reference type.

like image 40
Denis Kreshikhin Avatar answered Oct 04 '22 22:10

Denis Kreshikhin


Is it synonymous to asterisk?

Yes. Shift+8 on MY windows keyboard. Your example demonstrates why you shouldn't try to read C++ program aloud symbol by symbol. "Equals" in C++ is "==". "=" is assignment. Plus he forgot to tell about parentheses and semicolon. At this point (4 mistakes in single line of code) he could've written the damn thing silently.

It would have been much better if the dude read this part:

float f = *(float*)&i;

somewhat like this:

"Take pointer to i, C-style cast it into pointer to float, dereference, and assign value to float variable f". Makes much more sense that "star/asterisk" gibberish.

P.S. If you really love tongue twisters, you could try reading aloud any code that uses boost, iostreams, operator <<, casts, bitwise operations and "camel case" to distinguish between classes and methods. Such exercise will not improve your programming skills, of course...

like image 22
SigTerm Avatar answered Oct 04 '22 21:10

SigTerm