Talk:Function prototype

From Wikipedia, the free encyclopedia
Jump to: navigation, search
WikiProject Computing (Rated Start-class)
WikiProject icon This article is within the scope of WikiProject Computing, a collaborative effort to improve the coverage of computers, computing, and information technology on Wikipedia. If you would like to participate, please visit the project page, where you can join the discussion and see a list of open tasks.
Start-Class article Start  This article has been rated as Start-Class on the project's quality scale.
 ???  This article has not yet received a rating on the project's importance scale.
 

Rewrite/Check example[edit]

I just rewrote this page, and expanded it by a decent amount. I was considering removing the stub status, but I think that this page is in a grey area right now. Plus, I'm new here and I thought it better to leave such judgements to the more experienced Wikipedians.

One thing that should definitely be checked is the accuracy of the example in the "informing the compiler" section. The only C compiler I've used is gcc, so I don't know if other compilers behave in the same way. --seliopou 02:08, 4 Apr 2005 (UTC)

I don't think the example is really good. The compiler will always catch an error wherever the function is declared, with or without a prototype. It's like this:
int fac(int n) {             /* Called function  */
    if (n == 0) {
        return 1;
    }
    else {
        return n * fac(n - 1);
    }
}
int main() {                 /* Calling function */
    printf("%d\n", fac());   /* ERROR: fac is missing an argument! */
    return 0;
}
This will result in two errors - called from main, no matching function fac(void), candidate is fac(int); called from fac, fac(int) not declared.
While the other way round, an error will still be catched
int main() {                 /* Calling function */
    printf("%d\n", fac());   /* ERROR: fac is missing an argument! */
    return 0;
}
int fac(int n) {             /* Called function  */
    if (n == 0) {
        return 1;
    }
    else {
        return n * fac(n - 1);
    }
}
The compiler error message will say: from main, fac() not declared. So the whole thing is not a good example at all. It could be better if an argument is given to fac, making it say fac(10). --Deryck C. 02:32, 12 March 2007 (UTC)

Agree to Deryck. The example does not look brilliant as the result in compiler-dependent. Probably, a better example to explain the need for prototypes in something like:

int functionA(int n);
int functionB(int n);

int main()
{
    int n, res;
    /* do smth with n */
    res = functionA(n);
    return res;
}

int functionA(int n)
{
    /* do smth with n */
    if (/* some logic */)
    {
        n = functionB(n);
    }
    return n;
}

int functionB(int n)
{
    /* do smth with n */
    if (/* some logic */)
    {
        n = functionA(n);
    }
    return n;
}

- a very rough example, the idea behind is that both functionA and functionB recursively call each other in some circumstances (plus main calls functionA). Therefore, it's nice to have prototype declarations (at least, from codestyle point of view, even despite ingenious compiler you might have :). Rainor (talk) 08:59, 28 October 2008 (UTC)

Article is misleading[edit]

The article was misleading - it sounded like any function declaration is a prototype. I tried to clear up matters. Please check whether it is clearer now, and mark places that need discussion and/or citation.

I checked my changes against the C99 TC3 draft.

Then provide paragraph numbers and cite it - making unsourced edits and demanding that other people provide the citations isn't expected Tedickey (talk) 00:35, 28 August 2009 (UTC)
Not specific to C99, here is a discussion of "unspecified" versus "undefined" (there might be a copy of the corresponding text for C99 online; you're welcome to provide that source for discussion) Tedickey (talk) 00:44, 28 August 2009 (UTC)
Ok, i think you want a citation of my edit where i changed "unspecified" to "undefined.". I didn't know that one has to provide source-links, sorry i will do that in future on the discussion page. Here it goes: Paragraph 6.5.2.2/6 explicitly says that:

If the expression that denotes the called function has a type that does not include a prototype,.... If the number of arguments does not equal the number of parameters, the behavior is undefined. If the function is defined with a type that includes a prototype, and either the prototype ends with an ellipsis (, ...) or the types of the arguments after promotion are not compatible with the types of the parameters, the behavior is undefined.

Because behavior is undefined, we can't know whether the compiler won't complain. If the definition appears in the same translation unit, it's well possible that a good compiler complains about the incompatible argument types. Of course, if the expression denoting the function has a type that includes a prototype (declares the parameter types), then behavior is not undefined, and a diagnostic is required because the following rule appears as a constraint:

If the expression that denotes the called function has a type that includes a prototype, the number of arguments shall agree with the number of parameters. Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter.

That's why i changed the text to "behavior may be undefined" (it is undefined if the prototype declaration is commented out). Furthermore, a prototype can be contained in a defining declaration too. A prototype is the declaration of a function that includes the type of its parameters. A definition with a suitable parameter-type-list satisfies that all the way. That's why i removed the part in the introduction (see 6.2.1/2 for a citation of that).
As a last comment, i'm sorry for my poor english. Feel free to improve my wording. Litb me (talk) 00:50, 28 August 2009 (UTC)
I prefer the C rationale document, which explains things (undefined and unspecified behavior is also explained in the draft - but the description is rather short. The rationale document is much more elaborate): http://www.lysator.liu.se/c/rat/a.html#1-6 . A C99 version is available as a PDF document: http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf . It also explains that implicit function declarations don't exist in C99 anymore:

A new feature of C99: The rule for implicit declaration of functions has been removed in C99. The effect is to guarantee the production of a diagnostic that will catch an additional category of programming errors. After issuing the diagnostic, an implementation may choose to assume an implicit declaration and continue translation in order to support existing programs that exploited this feature.

—Preceding unsigned comment added by Litb me (talkcontribs) 01:11, 28 August 2009 (UTC)
I haven't TC3 at hand, but do have ISO/IEC 9899:1999 pdf. The wording is similar. However, the point of the "int foo(int)" is that omitting the prototype, the effect is almost the same since the type of the return-value is int, and the parameter(s) are also int (default promotion). So the case never gets into the clause about undefined behavior; 6.5.2.2/6 still blesses that. Tedickey (talk) 01:06, 28 August 2009 (UTC)
If the prototype were "char *foo(double bar)", then omitting that would result in undefined behavior. Tedickey (talk) 01:08, 28 August 2009 (UTC)
The implicit declaration has no parameter type list: The type of any argument that triggers an implicit declaration does not influence the function type of that declaration. The argument, however, will be of type int if you were to pass any argument that will be default-promoted to int. But you don't pass any argument at all. In main, you call the function with zero arguments - which is the point where the undefined behavior happens :) Litb me (talk) 01:15, 28 August 2009 (UTC)
I see that in the rationale (page 103, lines 33-35). For the standard itself, it is not so clear. Tedickey (talk) 09:34, 28 August 2009 (UTC)


But do you agree with me that you have overseen that in main the function is called *without arguments*? You assumed that the function is called with "parameter(s) [that] are also int". Of course, this yields to undefined behavior then. I should have been clearer with "The type of any argument that triggers an implicit declaration does not influence the function type". What i meant was "The type of any argument in a call that triggers an implicit declaration of the function does not influence the function type...". In any case, what you refer to (line 33-35) doesn't have anything to do with this all. It is similar to the "implicit int" rule, and refers to this situation:
void f(a) {
  /* a is implicitly assumed to 
   * have type int, because it's 
   * not declared */
}
In C99, such an old-style definition has to give a declaration for "a". In any case, "a" is a parameter, not an argument. Finally, what is your position on whether or not you agree with changing the wording to "undefined" and removing the introductory mentioning of "that omits a body"? (prototypes can appear in function *definitions* too). 84.174.237.26 (talk) 17:50, 28 August 2009 (UTC)
Regarding "undefined": The rationale refers to "constraint violation" (not "undefined"), to produce a "diagnostic". That doesn't appear to agree with "undefined". See page 18 (of the rationale), lines 23-29. The rationale prescribes behavior for this case; it is well-defined. (Bear in mind that the rationale is not the standard - perhaps the terse "remove implicit function declaration" on page 12 in the Foreward is standardese for the feature we're discussing, but it would be nice to point to something more substantial than that in the standard). Tedickey (talk) 00:41, 29 August 2009 (UTC)
I'm sorry i don't know what you refer to or what you want to clarify about "undefined". Please use section and paragraph numbers when referring to places in the rationale or standard. Regarding the changes i want to make: I gave section and paragraph numbers to the Standard. "Undefined behavior" is a violation of a "shall" that does not appear in a constraint, or behavior that is not explicitly specified or behavior that's explicitly specified as being undefined. In our case, the behavior is explicitly specified as being undefined. I assumed you know what it is before asking me that i should inform myself on the difference of it and unspecified behavior. Litb me (talk) 00:56, 30 August 2009 (UTC)
The rationale says that a diagnostic would be given, and that implementations are allowed to support the legacy feature. That matches the category on page 18 of the rationale for unspecified, rather than undefined. My comment to which you responded is that the standard itself does not appear to support the statement in the rationale, and suggesting that you might see some corresponding wording (in the standard itself) to tie things together. Tedickey (talk) 08:42, 31 August 2009 (UTC)
I haven't seen where in the rationale it says that a diagnostic would be given for the call to "fac()" (notice the zero arguments) in main. Please give a section and paragraph number for that. Also note that in case a violation within a constraint is explicitly specified as being undefined, a diagnostic must be given in addition, even though behavior is still undefined. (that's specified in 5.1.1.3/1 in the standard C99 TC3 draft). Also note that undefined behavior also allows supporting features whatever the implementation likes. Undefined behavior in fact allows doing *anything*. In any case, i would like to ask to move away from the rationale to the Standard. I gave section and paragraph numbers for my edit at the very beginning (6.5.2.2/6). If you can't find anything that says that paragraph doesn't state it's undefined behavior (and i, of course, very much doubt that), i will revert to my change of the article. Litb me (talk) 02:59, 1 September 2009 (UTC)
Wait, i think i know now where you refer to. Do you refer to my quote of the rationale? Well, that was *only* about implicit declarations. If you were to provide a declaration of "fac" without a prototype like "void fac();", then there is no diagnostic required, because there *is* a declaration in scope then. But behavior is still undefined when fac is called with zero arguments (6.5.2.2/6) Also note that behavior is not magically "unspecified" my merely saying that a diagnostic is given. A diagnostic is given for any violation of a constraint or any syntax rule. Also note that the whole code assumed C89 (not C99), and in C89 an implicit declaration would declare the function without using a prototype and would not require a diagnostic. Litb me (talk) 03:14, 1 September 2009 (UTC)
yes, I was referring to the rationale, page 69 lines 23-27 which you quoted, as well as page 103 lines 33-38. The current point of disagreement seems to be whether the behavior is "undefined" or "unspecified". (Noting that you're referencing TC3, ISO/IEC 9800:1999 does not contain either term). Thinking over that, I suppose there's more support for "undefined", since it states that the latitude associated with "unspecified" "does not extend as far as failing to translate the program". Tedickey (talk) 08:28, 1 September 2009 (UTC)
What i referenced of course contains the term "undefined": "...If the number of arguments does not equal the number of parameters, the behavior is undefined...". I showed it at the very start of the discussion :) Please don't give page and line numbers, they are ambiguous because their logical page numbers (printed on the bottom) differ from the physical page numbers of the PDF document and line numbers don't make clear whether to count whitespace lines etc - section and paragraph numbers are unambiguous. Regarding to p103, line 33 (assuming physical page number), i explained how that doesn't relate to our discussion (the code sample i gave "void f(a) { }". Page 69 line 23 also only refers to implicit declarations, which wasn't what we were discussing either - i only brought it into discussion to judge my insertion of "prior to C99" at the Start of the paragraph in the article. The paragraphs that are relevant to "unspecified -> undefined" were quoted by me out of the standard at the very start of the discussion. But i'm glad to see that we seem to come to an agreement finally :) Litb me (talk) 16:25, 1 September 2009 (UTC)
sounds okay Tedickey (talk) 21:08, 1 September 2009 (UTC)

java via questions by cjet 88[edit]

1. what is a programming paradigm? Ans: Fundamental style of computer programming. It serves as a pattern or model for a programming language

2. what are the Procedural oriented features? Ans ->Procedural programming is a programming paradigm,derived from structured programming. ->It is based upon the concept of the procedure call. Procedures also known as routines, subroutines, methods, or functions

3. What are the OOPs concepts? Ans: OOPs (Object Oriented Programming System) java oops concepts Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:Object

                                                                 Class
                                                              Inheritance
                                                              Polymorphism
                                                              Abstraction
                                                              Encapsulation

4. What are the features of Java? Ans:There is given many features of java. They are also known as java buzzwords. The Java Features given below are simple and easy to understand.

   1.Simple
   2.Object-Oriented
   3.Platform independent
   4.Secured
   5.Robust
   6.Architecture neutral
   7.Portable
   8.Dynamic
   9.Interpreted
   10.High Performance
   11.Multithreaded
   12.Distributed

5. List out some of the tools in JDK? Ans: JDK: java Developement Kit using some important tools are javac: Java Compiler Java: Java Interperter jar:creates a jar file jdb:java debugger javap:java disassembler javah:makes a c routine header file javadoc:creates HTML Documentation rmic:runs java applets rmiregistry:Remote object registry service.

6. What is JRE? Ans: JRE: java runtime environment on which java app rans, it converts byte code into machine code on which it is excuited

7. Explain Java Platform? Ans: -> A set of Modules -> Provides can environment to complie and executed java programs. -> Acts as a buffer between a running java programs and the underlying h/w and os.


8. What is JVM? Ans: JVM (Java Virtual Machine) Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).

9.What is JVM? Ans -> JVM specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.

    -> An implementation Its implementation is known as JRE (Java Runtime Environment).
    -> Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.

10. What is meant by Robust? Ans: Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust.

11. What is difference b/w class and object? Ans : class is an instance of an object. object is an ref variable to a class.

12. What are the data types in Java? Ans : 8 data types in java 1.Byte 2.Short 3.Int 4.Long 5.Char 6.Float 7.Double 8.Boolean

13. Why does char datatype in java takes 2 bytes of memory? Ans : java supports 16-bot unicode chrecter encoading,in that scheme of representing char takes 2 bytes of memory

14. What is UNICODE? Ans : it is one type of ENCOADING system which handle about the text expressed in writing the code.

15. What are versions of Java? Ans : -> JDK 1.1 -> J2SE1.2 -> J2SE1.3 -> J2SE1.4 -> java SE5.0 -> java SE6 -> java SE7 -> java SE8

16. Write the features of jdk1.5 and jdk1.6? Ans :


17. Explain JVM architecture? Ans : Class Loader Sub System: The class loader sub system will take a .class file as the input and verify (Byte code) into the JVM.There are 5 different areas:

1.Method Area: This Area can be used for storing all the class code and method code.

                   All classes bytecode is loaded and stored in this run time area ,and all static variables are created in this area.

2.Heap Memory: This Area can be used for storing all the objects that are created.

                   It is the main memory of JVM , all objects of classes  are created non static variables memory are created here.

3.Java Stack area: This Area can be used for storing the information of the methods. All Java methods are executed.

                   In this stack area Jvm creates threads ,such as main thread and user defined thread.
                Main thread responsible to execute java methods starts with main method.
 

4.PC Register (program counter) area: This Register will contain address of the next instruction that have to be executed.

5.Java Native Stack: This area is used for storing .

Execution Engine:

           It creates main Thread in java stack.
                It is responsible for executing the program.

18. What is meant by platform independant? Ans : we say a progarmme is platform independent when it is created and compiled in one platform,and executed in another platform.

19. What is initial name of Java? Ans : JDK is the intial name of java

20. What is use of Java API? Ans : API mean application programming interface. it is set of classes included with java devoleped environment.these classes are written using java language and run on JVM and act like interface.


21. What are the tokens of Java? Ans: Tokens are low level language elemnts

           There are 6 tokens in java...
        -tokens such as

Identifiers Keywords Literals Operators Separators WhiteSpace Charact

22. What are the convension rules to write elements in Java? Ans: Here some conversion rules to write elements in java Constants:All letters are capitals Packages:All letters are small letters Class/Interface:First letter of every word is capital Variables/Methoda:First letter of every word is capital except for first word

23. Write the keywords in Java? Ans: There are 50 keywords in java.. abstract,continue,for,new,switch,assert,default,float, package,synchronized,boolean,do,if,private,this,break, double,implements,protected,throw,byte,else,import, public,throws,case,enum,instanceof,return,transient, catch,extends,int,short,try,char,final,interface,static, void,class,finally,long,strictfp,volatile,super,native,while remaining two keywords are currently not used in java i.e; const and goto

24. What are the keywords not in use right now? Ans: continue and goto keywords are not in use now.

25. What are the pre-defined literals in Java? Ans: Boolean literals are pre-defined i.e(True and False)

26. What are the different literals in Java? Ans: Literals are:Numerical literals(Integer and Floating) Character literal String literal Boolean literal(True and False)

27. What is type casting? When type casting in possible? Ans: Converting one type of value to another type is called as type casting

    -Type casting is possible if the nature of source and destination variables are same

28. What are different types of type casting? explain. Ans:Type casting is of two types 1)Implicit type casting 2)Explicit type casting

    ->Implicit type casting is done by compiler automatically when the width of destination is greater than source
               ex: int x=10;
                double y;
                y=x;          // then value of y is 10.0
   ->Explicit type casting is if width of destination is less than the source   then explicit type casting is required
     For this we use type cast operator
       ex:      int x;
                double y=10.5;
                 x=(int)y;         //then x value is 10
   

29. Write the general structure of class in Java? Ans: We build class to create objects

    -Structure of class:

class <classname> { datatype variablename[=value]; datatype variablename[=value]; returntype functionname([arglist]) {

                    //body

} }

30. How to create an object? Explain. Ans: Objects are created dynamically in java 'new' keyword is used to create object First we have to create a reference variable Syntax: <classname> refernce; Syntax for creating object: reference=new classname();

31. what is displayed, When an object reference is print? Ans : classname at hash code

32. What is meant by reference variable? Ans: Reference variables are the variables that hold address of object.It is also called Object reference

33. What are the default values of primitive types and reference type when they are not initialized by programmer? Ans: Default values of primitive data types are: int-0 char-space Double-0.0 boolean-False

    Default value for reference data type is:reference-Null

34. What happend when an objetc is created? Ans: -When an object is created some space is allocated in Heap memory of JVM

    -Instance variables of that class are loaded into the memory
    -Instance variables are initialised by JVM with default values
    -The address of memory is returned

35. What is a constructor? Ans: Constructor is a special method in a class

   ->The name of the constructor is class name.It does not have any return type not even void 
   ->constructor is invoked when an object is created 

36. What is meant by Constructor overloading? Ans: Writting more than one constructor in a class with different set of parameters is called constructor overloading

    -> the overloaded constructor should differ in any of the following

1)Type of parameters 2)Order of parameters 3)No.of parameters

37. What is use of contrustor overloading? Ans: construvtor overloading is used to allow one object to initialize another

    It is used to construct objects in different ways

38. What is use of Constructor? Ans: Constructor is used to give default state to the object at the time of creation. i.e,to initialise an instance variables


39. What is default constructor? Ans: if a programmer does not write any constructor in a class then compiler provides a constructor that constructor is called as default constructor

                   ->constructor with no parameters is also called as default constructor.

40. What is this keyword? Ans: 'this' keyword refers to an object on which the method is invoked i.e to know the object inside a method on which it is invoking

41. What are the uses of this keyword? Ans: 'this' keyword is used for 1) To access hidden instance variables of a class 2) To invoke constructor from another constructor of same class

42. Why the variables are called as instance variables? Ans: If the variables are defined without 'static' keyword and are outside any method declaration are object specific.so they are called as instance variables

43. How many public classes can we write in a source file? and Why? Ans: We can have atmost one public class and any number of non-public classes in a source file because it throws one Exception

           ->The exception deals with inner classes.if you have more than one public class it results in difficult to manage code and decreases its re-           usability.

44. What is meant by main class? Ans: A class is a blue print from which individual objects are created.it describes set of objects with common behavior

45. How many ways arguments are passed to a method?What are they? Ans: Arguments are passed to a method using pass by value and pass by reference

46. What are the different types of variables in Java? Ans: 3 Types: 1.Class Variable/Static Variable 2.Instance Variable/NonStatic Variable 3.Method Variable/Local Variable

47. What is use of new operator? Ans: It is an array of array. It contains 2 Subscripts([][]).

      1.[]-->It contains no.of arrays.
      2.[]-->It contains no.of elements in each array.

48. What are the access modifiers allowed in the class declarator? Ans: 11 Types: 1.Public 2.Private 3.Volatile 4.Protected 5.Static 6.Final 7.Abstract 8.Synchronized 9.Native 10.Strictfp 11.Transient

49. How many object can we create for a class? Ans:We can create no.of objects.

50. What is meant by class instantiation? Ans:Class is instantiated when object is created. — Preceding unsigned comment added by Himath9032 (talkcontribs) 12:06, 20 July 2015 (UTC)