Is a function without input/output a procedure? [duplicate] - c++

This question already has answers here:
What is the difference between a "function" and a "procedure"?
(18 answers)
Closed 8 years ago.
I read many many articles about difference between function and procedure but there is something I'm in doubt about.
Do we call following statement a function or a procedure in terminology?
void f() { return; }
Some articles says function returns value but procedure does not.
Some other article says if a function returns one value called function but if it returns more than one value it called procedure.

In the standard terminology of C and C++, no. It's a function whether or not it returns anything, or even if it doesn't return.
In more general computing vocabulary, and the terminology of other programming languages, it might be called a "procedure" or a "subroutine" (and perhaps a few other terms) if it doesn't return a value.

A procedure is a function that do not return a result!

There is no such term as procedure in C and C++ languages. So relative to C and C++ languages your question has no sense. In any other languages the definition of the term procedure can vary.
In C and C++ statement
void f() { return; }
is a function definition.

As Mike annd Grzegorz says, from C Standard point of view there is no difference, but the function term is used by convention.
In other programming language (e.g. basic) that distinction is commonly used depending if return or not a value that function.
As final note: in the C Programming Language book (official C programming language book) from Dennis Ritchie (C creator) the term function is used independently if returns or not a value and that's one of the reason that the term is used indistinctly.

There are various terminologies that means the same in various different languages. Like function used in structured language like c, Method's used in java, procedure, function both used in Scala.
In reality, Procedure is a function really but that doesn't return anything and in C we still refer to it as function.

From the C Standard point of view there is no distinction between functions and procedures (like in e.g. Pascal) or subroutines (like in e.g. Fortran). Both types (i.e. returning void and non-void) are simply named as functions. I believe that C++ just follows this way.

Related

Why is C++'s void type only half-heartedly a unit type?

C++'s void type is not uninhabited. The problem is that while it has precisely one inhabitant, very much like the Unit type (a.k.a. ()) in ML-like languages, that inhabitant cannot be named or passed around as an ordinary value. For example, the following code fails to compile:
void foo(void a) { return; }
void bar() { foo(foo()); }
whereas equivalent (say) Rust code would compile just fine:
fn foo(a : ()) { return; }
fn bar() { foo(foo(())); }
In effect, void is like a unit type, but only half-heartedly so. Why is this the case?
Does the C++ standard explicitly state that one cannot create values of type void? If yes, what is the rationale behind this decision? If not, why does the code above not compile?
If it is some backwards-compatibility related reason, please give a code example.
To be clear, I'm not looking for work-arounds to the problem (e.g. using an empty struct/class). I want to know the historical reason(s) behind the status quo.
EDIT: I've changed the syntax in the code examples slightly to make it clear that I'm not trying to hijack existing syntax like void foo(void) (consequently, some comments may be out of date). The primary motivation behind the question is "why is the type system not like X" and not "why does this bit of syntax not behave as I'd like it to". Please keep this point in mind if you're writing an answer talking about breaking backwards compatibility.
"Does the C++ standard explicitly state that one cannot create values of type void?"
Yes. It states that void is an incomplete type and cannot be completed. You can't create objects or values with an incomplete type.
This is an old rule; as the comments note it's inherited from C. There are minor extensions in C++ to simplify the writing of generic code, e.g. void f(); void g() { return f(); } is legal.
There seems to be little gain in changing the status quo. C++ is not an academic language. Purity is not a goal. Writing useful program is, but how does such a proposal help with that? To quote Raymond Chen, every proposal starts at -100 and has to justify its addition; you don't justify the lack of features.
That is really an historical question. Old (pre-C) language used to differentiate functions which returned values, from subroutines which did not (ooh, the good old taste of Fortran IV and Basic...). AFAIK, early C only allowed functions, simply functions were by default returning int and it was legal to have no return statement (mean return an unspecified value) and legal to ignore any return value - so that the programmer can write coherent code... In those early days, C was used more or less as a powerful macro assembler, and anything was allowed provided the compiler can translate it into machine instructions (no strict aliasing rule for example...). As the memory unit was char, no need for void * pointer, char * was enough.
Then people felt the need to make clear that a buffer was expected to contain anything and not a character string, and that some functions will never return a value. And void came to feel the gap.
The drawback, is that when you declare a void function, you declare what was called a subroutine, that is something that can never be used as a value, in particular never be used as a function parameter. So void is not only a special type that can never be instantiated, it really declare that the result cannot be a member of an expression.
And because of language inheritance, and because the C standard library is still a subset of the C++ standard one, C++ still processes void the way ANSI C did.
Other languages can use different conventions. In Python for example a function will always return something, simply it returns the special None value if no return statement is encountered. And rust seem to have still another convention.

Is the term "method" defined by the C++ Standard?

The term "method" is often used to discuss C++ code. Does the standalone term have a well-defined meaning in C++ or is it ambiguous? Is it acceptable to use the term by itself, or should it be qualified (e.g. a "class method" or "virtual method"), or should it be simply avoided altogether?
The term method is not defined in the C++ standard. The terminology uses member function instead.
Bjarne Stroustrup however defines the term method in his own glossary as virtual member function. So this shows evidence that the term is acceptable.
I would avoid this term entirely, as it is clear what you mean by "member function", but not "method" - that you asked this question is proof enough.
However, normative appearances of the word "method" in the C++14 standard are
In the content list:
17.5 Method of description (Informative)
This is repeated in the title of that section.
[basic.compound]:
These methods of constructing types can be applied recursively;
[cpp.include]
The method by which a sequence
of preprocessing tokens between a < and a > preprocessing token pair or a pair of " characters is combined
into a single header name preprocessing token is implementation-defined.
[library.general]
The following subclauses describe the definitions (17.3), method of description (17.5), [..]
In table 32, FLT_EVAL_METHOD is mentioned.
In stage 2 of num_get's do_get:
For arithmetic types, punct.thousands_sep() characters are inserted
into the sequence as determined by the value returned by
punct.do_grouping() using the method described in 22.4.3.1.2
[forwardlist.modifiers]:
Otherwise, inserts sz - distance(begin(), end()) elements at the end of
the list such that each new element, e, is initialized by a method equivalent to calling allocator_traits<allocator_type>::construct(get_allocator(), std::addressof(e), c).
[filebuf.virtuals]:
Behaves according to the description of
basic_streambuf<charT,traits>::uflow(), with the specialization that a
sequence of characters is read from the input with the same method as
used by underflow.
The term is clearly never referring to a "member function".
The C++ standard makes no mention of the term method. It should be noted that the official C++ FAQ does make use of this term, but to describe a virtual function; a simple Google search reveals more occurrences of this term.
I've never seen the term method in an IDE (Visual Studio), but I've seen the term member function. In my opinion method is a 'one size fits all' term.
The term method had been historically used as a synonym of the procedure of an object. Considering, an object has both data and behaviour, it is this behaviour which was referred as method.
Tracing backward, I could find a reference to the usage of the term method when referring to an MIT ALGOL version, AED-0
Quoting wikipedia
MIT ALGOL version, AED-0, linked data structures ("plexes", in that
dialect) directly with procedures, prefiguring what were later termed
"messages", "methods", and "member functions".
Over the years method had been an integral part of Object Oriented Analysis and Design and Object-oriented programming. Now C++ evolved as a procedural language where it extended C a procedural language to have object oriented capabilities. C had the concept of structure, and the data elements were called members. Refer Methods in C++.
To not break the lineage, C++ continued to call the elements of structured and the newer genre class as members.
Now, to differentiate between data and functions, instead of introducing a new terminology, it extended this terminology to call data members and member functions. Member functions which supported dynamic binding were called virtual functions.
So, strictly speaking, official references refrains from using the terminology methods when referring to member functions. The terminology is most prevalent among the people who have a more Object Oriented background. So if you want to remain unambiguous, it is best to use the terminology as
data member
member function
virtual functions
Here my analysis regarding the word method.
I did a scan on official documentation (standards, specifications, etc.) on several programming languages.
http://componentsprogramming.com/using-the-right-terms-method/
Adequate taxonomy (not dependent on any programming languages) will be published in a future article.
Regarding to C++, the correct terminology is: member/non-member function.
Some people use member/free functions.

Parameter Passing Techniques in C/C++

There are different parameter passing techniques like - Call By Value, Call By Reference, Call By Value Result, Call By Name, Call By Text and Call By Need in Programming Languages.
I have seen implementations of Call By Value and Call By Reference in C/C++; but the other techniques were taught only with simple plain examples, where we are given that this example uses say "Call By Value Result" and so answer accordingly. I was wondering whether the other techniques have ever been implemented in C/C++ or any other languages or were they just theoretical?
C provided and still provides pass by value only.
In C++ it's only by value or by reference. The other techniques can be simulated using existing C++ language constructs - specially crafted conversion operators and constructors.
Check this the diff usage of parameters passing technique
http://c2.com/cgi/wiki?ParameterPassing

How does calling a method in Objective-C differ from C++? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Objective C message dispatch mechanism
My question IS NOT about the syntax. I'd like to learn how is calling a method in C++ different from sending a message to an object in Objective-C and how they are performed?
This is quite a complicated question, as there is no fix C++ calling convetion unlike C.
Objective-C is just a thin wrapper around C, so it uses the same convention.
Just one additional thing to now, when you send a message like:
[target selector];
It is the same as:
objc_msgSend(target, #selector(selector));
Then it's just the traditional C calling convention, with a first table lookup for the function matching your message. The objc_msgSend is a bit more complicated as it keeps the arguments stack in place and pass it directly to the underlying function.
The C++ calling convention differs from one name-mangling to another, and even from one compiler to another.
From a performance point of view, C++ method call is faster as the link is resolved at compile-time (more exactly at link-time). The method either exists or not, which cause a linker error.
Objective-C method call include a method table lookup at runtime, thus your method may be added later in your code, which gives more flexibility but less performance.
Entirely the same and entirely different. In C++ you'd say
result = myObjectPtr ->myMethod(myParm1, myParm2);
In Objective-C you'd say
result = [myObjectPtr myMethodWithParm1:myParm1 andParm2:myParm2];
In the simple case they'd function the same, from an external appearances standpoint, but lots of differences at the implementation level, since Objective-C calls are dynamic.
It would take several pages to enumerate all the differences in any detail (though for the simplest cases the differences aren't significant).

Do we still need subroutines? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
In Fortran, a clear difference exists between function and subroutine: functions return one value, subroutines return no value. This introduce a cascade of differences between the two. One example is the calling semantics: you can call a function just as in other languages, but in order to call a subroutine you must issue a call statement first.
With the addition of pointers and data types in Fortran95, it appears that there is no technical limitation in making any subprogram a function, and keeping subroutines just for legacy. Functions could return zero (you just return a dummy integer), one, or multiple values (for example, you could return a pointer to an allocated instance of a type, like a C++ STL Pair).
Am I wrong? Do we still need subroutines in Fortran programming due to some feature that subroutines have and functions don't?
If you search the comp.lang.fortran archives, you'll find discussions about the semantics of functions. IIRC it turns out that it's not clearly specified in the standard what is and what isn't allowed for functions that have side-effects.
For instance, can the compiler optimize
x = foo(args) + foo(args)
into
x = 2 * foo(args)
Or for another example, consider
x = y + foo(y)
What if foo() changes the value of y? Remember that Fortran doesn't have the C concept of sequence points.
In general, the recommendation by several experts is to use functions only if they're pure, otherwise use subroutines. And, that is advice that I follow myself as well.
I don't think subroutines are going anywhere. Most other languages allow methods that do and do not return values. I can't see any reason why that's a bad thing. No one should be moved to change a thing.
Legacy alone says that subroutines will persist as long as Fortran does. And as long as Fortran is around, there'll be nothing wrong with writing a method that performs an action and returns nothing.
UPDATE:
Why do you say "hassle"? What's the big deal? I disagree with the idea that subroutines are a "hassle" when they're used in an appropriate situation.
Fortran has maintained a distinction between functions and subroutines since version 77 and probably earlier. Other C-family languages do, too. Why is this suddenly such a hassle? Even the languages that have had pointers and objects for a long time have methods that return void.
You're trying to program C in fortran again, aren't you? ;-)
In my opinion, yes - we do. For if for one reason only - they're easier to grasp, to understand, and they're more widely used than functions.
Also, -1, for I believe this is not a constructive question. If you don't like them, then don't use them.
If I understand correctly Stefano is not against the idea of subroutines. The opinion against them is nonsense. He against the usage of different styles for subroutines/functions.
Fortran is imperative programming language. More precisely it is a procedural programming language (and even more precisely it is structured programming language).
In imperative programming we have a state and statements to change it. In procedural programming our tools to do changes are procedures (we localize changes inside procedures). The procedure may or may not return some value. And I don't think that this fact (either procedure return value or not) is so significant reason to have 2 different entities in the programming language. We can have only functions (like in C) and just return something special when we do not actually need to return something (void). Or we can have only procedures and special syntax permitting to return values like in Modula-2, Oberon, ...
The language probably should have only one style to declare procedures. I agree with You, Stefano.
The fact that I have to answer myself to this question is insane, but that's how it is.
The difference stems from the fact that you cannot "call functions like in other languages" in Fortran. While in C you can call an integer function without assigning the value, example
int foo() {
return 5;
}
int main() {
foo(); // this works
}
In Fortran, you always have to associate a receiving variable. Example
module test
implicit none
contains
integer function foo()
print *, "hello"
foo = 0
end function
end module
program hello
use test
integer :: x
x = foo() ! this works
foo() ! this does not compile
end program hello
Meaning that to "emulate" a void function by returning a dummy integer would still not allow you to call without having a receiver variable.
In Fortran, the void return type does not exist. Technically, you could structure your program with all functions, replace every occurrence of the call statement with x = like seen above, but that would not make your syntax similar to C or other languages anyway, where there is no distinction between void-returning functions and non-void returning functions. subroutines are the only entities that allow to "return void", but the semantic to perform the call is simply different. Apart from that, there's no difference between the two.