1.

Explain the difference between a function declaration and function definition. 

Answer»

Function declaration and Function definition: 

A function declaration contains the name of the function, a list of variables that must be passed to it, and the type of variable it returns, if any. For example in the following program in line 2, the function cube is declared. The variables to be passed to the function are called arguments, and they are enclosed in parentheses following the function's name. In this example, the function's argument is long x. The keyword before the name of the function indicates the type of variable the function returns. In this case, a type long variable is returned. The function itself is called the function definition. In the following example, a function cube is defined from line 13 to 18.A function definition has following several parts: 

•Function header: The function starts out with a function header on line 13. The function header is at the start of a function, and it gives the function's name, the function's return type and describes its arguments. The function header is identical to the function declaration minus the semicolon.

• Function Body: The body of the function, lines 14 through 18, is enclosed in braces. The body contains statements that are executed whenever the function is called. Local variables are declared within a function body. Finally, the function concludes with a return statement on line 17, which signals the end of the function and it passes a value back to the calling program. 

The following program uses a function to calculate the cube of a number.

1: #include 

2: long cube(long x); 

3: long a, result; 4: main() 

5: { 

6: printf("Enter an integer value: "); 

7: scanf("%d", &a); 

8: result= cube(a); 

9: printf("\nThe cube of %ld is %ld.\n", a, result); 

10: } 

11: 

12: /* Function: cube() - Calculates the cube value of a variable */ 

13: long cube(long x) 

14: { 

15: long y; 

16: y = x * x * x; 

17: return y; 

18: } 



Discussion

No Comment Found

Related InterviewSolutions