user842225
user842225

Reputation: 5979

Conflicting types issue

I am following the book to create a simple C program, the following code is from the book :

#include <stdio.h>

int main(int argc, const char * argv[])
{

    congratulateStudent("Kate", "Cocoa", 5);

    return 0;
}

void congratulateStudent(char *student, char *course, int numDays) {
    printf("%s has done as much %s Programming as I could fit into %d days.\n",
           student, course, numDays);
}

After I copy & paste the above code to my XCode, I got error:

Conflicting types for 'congratulateStudent'

I noticed there is another person has the same problem with the book's code , I tried the accepted answer, changed the code to :

void congratulateStudent(char *student, char *course, int numDays) {
        printf("%s has done as much %s Programming as I could fit into %d days.\n",
               *student, *course, numDays);
    }

But the compiler error is still there, what is wrong?

Upvotes: 2

Views: 3105

Answers (4)

Nick Louloudakis
Nick Louloudakis

Reputation: 6005

Add a function declaration before main:

void congratulateStudent(char *student, char *course, int numDays);

UPDATE 1: You can alternatively move the congratulateStudent function before main.

UPDATE 2: The answer that you refer to in the link, focuses on that the user uses wrong argument types in the function than those he/she intends to use in: char, char, int and that %s, %s, %d used in printf work for char*, char*, int types, so this is something different.

Upvotes: 4

Degustaf
Degustaf

Reputation: 2670

You should make sure your compiler's warning flags are set: -Wall -Wextra. Those should have given you a warning that the compiler didn't understand the function congratulateStudent within main. My compiler gave me the output

line 6: warning: implicit declaration of function `congratulateStudent'

These sorts of warnings can help you figure out where your mistakes are.

And, to fix both the warning and the error, we can add a function prototype near the top of the code:

#include <stdio.h>

void congratulateStudent(char *student, char *course, int numDays);

int main(int argc, const char * argv[])
{
...

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

It's because in your main function, the congratulateStudent function was not declared yet, and the compiler assumes it returns int by default, then you define it below to return void, hence the

Conflicting types for 'congratulateStudent'

so either declare the function before main or move it's definition before main, both solutions work.

Upvotes: 3

Prerak Sola
Prerak Sola

Reputation: 10009

Try this:

#include <stdio.h>

void congratulateStudent(char *student, char *course, int numDays) {
   printf("%s has done as much %s Programming as I could fit into %d days.\n",
       student, course, numDays);
}

int main(int argc, const char * argv[])
{

congratulateStudent("Kate", "Cocoa", 5);

return 0;
}

Upvotes: 0

Related Questions