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

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

"foofbar1.cc:71...: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'int' [-Wformat=]
   printf ("y is a %s\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, integers 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 %s\n", y);

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

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

The "%s" is appropriate for printing string variables.  For integer variables, use "%d" 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 *