Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Noncompliant code example uses the identifier-list form for parameter declarations.

Code Block
bgColor#FFCCCC
langc
int max(a, b)
int a, b;
{
  return a > b ? a : b;
}

...

In this compliant solution, int is the type specifier, max(int a, int b) is the function declarator, and the block within the curly braces is the function body.

Code Block
bgColor#ccccff
langc
int max(int a, int b) {
  return a > b ? a : b;
}

...

In this noncompliant code example, the definition of func() in file_a.c expects three parameters but is supplied only two.

Code Block
bgColor#FFCCCC
langc
/* file_a.c source file */
int func(int one, int two, int three){
  printf("%d %d %d", one, two, three);
  return 1;
}

However, because there is no prototype for func() in file_b.c, the compiler assumes that the correct number of arguments has been supplied and uses the next value on the program stack as the missing third argument.

Code Block
bgColor#FFCCCC
langc
/* file_b.c source file */
func(1, 2);

...

This compliant solution correctly includes the function prototype for func() in the compilation unit in which it is invoked, and the function invocation has been corrected to pass the right number of arguments.

Code Block
bgColor#ccccff
langc
/* file_b.c source file */
int func(int, int, int);

func(1, 2, 3);

...

In this noncompliant code example, the function pointer fn_ptr refers to the function add(), which accepts three integer arguments. However, fn_ptr is specified to accept two integer arguments. Setting fn_ptr to refer to add() results in unexpected program behavior. This example also violates the rule DCL35-C. Do not invoke a function using a type that does not match the function definition.

Code Block
bgColor#FFCCCC
langc
int add(int x, int y, int z) {
   return x + y + z;
}

int main(int argc, char *argv[]) {
   int (*fn_ptr) (int, int);
   int res;
   fn_ptr = add;
   res = fn_ptr(2, 3);  /* incorrect */
   /* ... */
   return 0;
}

...

To correct this example, the declaration of fn_ptr is changed to accept three arguments.

Code Block
bgColor#ccccff
langc
int add(int x, int y, int z) {
   return x + y + z;
}

int main(int argc, char *argv[]) {
   int (*fn_ptr) (int, int, int) ;
   int res;
   fn_ptr = add;
   res = fn_ptr(2, 3, 4);
   /* ... */
   return 0;
}

...