How to resolve "conflicting types error" in C?
c
Solution
The problem is that `swap` was not declared before it is used. Thus it is assigned a "default signature", one which will in this case not match its actual signature. Quote Andrey T:
The arguments are passed through a set of strictly defined conversions. `int *` pointers will be passed as `int *` pointers, for example. In other words, the parameter types are temporarily "deduced" from argument types. Only the return type is assumed to be `int`.
Aside from that, your code produces a bunch of other warnings. If using `gcc`, compile with `-Wall -pedantic` (or even with `-Wextra`), and be sure to fix each warning before continuing to program additional functionality. Also, you may want to tell the compiler whether you are writing ANSI C (`-ansi`) or C99 (`-std=c99`).
Some remarks:
- Put spaces after commas.
- Make `main` return an `int`.
- And make it `return 0` or `return EXIT_SUCCESS`.
- Import the definition of `getch`: `#include <curses.h>`.
- Or just use `getchar`.
- Import the definition of `memcpy`: `#include <string.h>`.
- Don't return something in a `void` function.
You may want to use `malloc` to allocate a buffer of variable size. That will also work with older compilers:
void swap(void *p1, void *p2, int size) {
void *buffer = malloc(size);
memcpy(buffer, p1, size);
memcpy(p1, p2, size);
memcpy(p2, buffer, size);
free(buffer);
}
Problem
For the following C code (for swapping two numbers) I am getting the "conflicting types" error for `swap` function: ``` #include <stdio.h> #include <stdlib.h> int main() { int a,b; printf("enter the numbers to be swapped"); scanf("%d%d",&a,&b); printf("before swap"); printf("a=%d,b=%d",a,b); swap(&a,&b,sizeof(int)); printf("after swap"); printf("a=%d,b=%d",a,b); getch(); } void swap(void *p1,void *p2,int size) { char buffer[size]; memcpy(buffer,p1,size); memcpy(p1,p2,size); memcpy(p2,buffer,size); return(0); } ``` Compiler diagnostics: ``` <source>:10:6: warning: implicit declaration of function 'swap' [-Wimplicit-function-declaration] swap(&a,&b,sizeof(int)); ^~~~ program:15:6: warning: conflicting types for 'swap' void swap(void *p1,void *p2,int size) ^~~~ ``` Can anybody tell why that error is coming? What is the solution for that?