PKG
PKG

Reputation: 589

Operators vs Functions in C/C++

Someone recently asked me the difference between a C++ standard operator (e.g. new,delete,sizeof) and function (e.g. tan,free, malloc). By "standard" I mean those provided by default by the compiler suite, and not user defined. Below were the answers I gave, though neither seemed satisfactory.

(1) An operator doesn't need any headers to be included to use it : E.g. you can have a call to new without including any headers. However, a function (say free() ) does need headers included, compulsorily.

(2) An operator is defined as such (ie as a class operator) somewhere in the standard headers. A function isn't.

Can you critique these answers and give me a better idea of the difference?

Upvotes: 20

Views: 10453

Answers (6)

Siva Prakash
Siva Prakash

Reputation: 4997

An operator is compiled to a sequence of instructions by the compiler.

When the code calls a function, it has to jump to a separate piece of code

Upvotes: 9

Shrihari Bhat
Shrihari Bhat

Reputation: 39

An operator and function are conceptually same. Both of them take some values as input and return some as output. They only difference is there syntax.

Upvotes: 3

sowrov
sowrov

Reputation: 1050

to my understanding function name is a representation of goto operator, after jumping to a specific code location application can perform one to many unit of work, on the other hand an operator perform an actual unit of work.

Upvotes: 0

sbi
sbi

Reputation: 224199

Operators are keywords with a fixed syntax. Those which can be overloaded might vary a bit in syntax, but that's within the boundaries. The new operator is still spelled new, even when overloaded and the syntax of invoking it is always the same.

Function names are identifiers, which can be almost arbitrary. There's no syntactic reason you couldn't do away with malloc() and use

bool my_fancy_alloc(void*& memory, unsigned char size, bool zero_it);

instead. (Mark: There are other reasons, though. Like your fellow-workers' sanity.)

Upvotes: 20

Dennis Zickefoose
Dennis Zickefoose

Reputation: 10979

(1) isn't strictly true. typeid is an operator, but its use requires that you include <typeinfo>.

My answer would simply be that operators are defined as such. :: doesn't necessarily need to be considered an operator, for instance, but the standard says it is, and so it is.

If you're looking for a more verbose answer, I would go on to mention that operators mostly do not look like functions. And those that do [sizeof and typeid] don't act as functions; their operands are not evaluated at runtime.

Upvotes: 4

Matt Curtis
Matt Curtis

Reputation: 23624

Operators have special syntax, e.g. you can use new (or +) without putting arguments in brackets after the operator name.

Upvotes: 2

Related Questions