How Do You Troubleshoot a C Program That Prints a Warning Message like “expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]”?

Problem scenario
You compile a C program (with gcc foobar.cc) but you get an error message like this:

basicprog.c:5:13: warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]
printf ("y is a %d\n",y);

What do you do to not get this error?

Solution
While the code compiles, the executable may not run.  A compilation error can be benign.  For this case, string characters need a special syntax to be printed out.  

Here is a line that will produce this error (with a variable named "y"):

   printf ("y is a %d\n", y);

Here is a similar but corrected line that will be error free:

  printf ("y is a %s\n",y);

The "%d" is appropriate for printing integer variables.  For string variables, use "%s" syntax.


For learning about the C programming language, you may want to purchase a book below:

0131103628C Programming Language, 2nd Edition by Pearson
1718501048Effective C: An Introduction to Professional C Programming by No Starch Press
1789349915Learn C Programming: A beginner's guide to learning C programming the easy and disciplined way by Packt Publishing
1789343623Extreme C: Taking you to the limit in Concurrency, OOP, and the most advanced capabilities of C by Packt Publishing
0393979504C Programming: A Modern Approach, 2nd Edition by W. W. Norton & Compan

Leave a comment

Your email address will not be published. Required fields are marked *