Question:
C programming, printf calls help please?
Kenny B
2012-03-19 00:19:19 UTC
Given the following declarations:
char *message = "Programming in C is fun\n";
char message2[] = "You said it\n";
char *format = "x = %i\n";
int x = 100;

determine whether each printf call from the following sets is valid and produces
the same output as other calls from the set.

/*** set 1 ***/
printf ("Programming in C is fun\n");
printf ("%s", "Programming in C is fun\n");
printf ("%s", message);
printf (message);
/*** set 2 ***/
printf ("You said it\n");
printf ("%s", message2);
printf (message2);
printf ("%s", &message2[0]);
/*** set 3 ***/
printf ("said it\n");
printf (message2 + 4);
printf ("%s", message2 + 4);
printf ("%s", &message2[4]);
/*** set 4 ***/
printf ("x = %i\n", x);
printf (format, x);



I'm completely stumped. I doubt it but does anyone know which sets are valid??
Three answers:
2012-03-19 00:21:42 UTC
They are all valid.



EDIT: Just to clarify, all of the calls to printf are valid. Also, all of the calls within any given set produce the same results as each other. There are a few minor issues with your code, however. Firstly, since you're assigning a string literal or message and format, their types should be "const char *". Secondly, given the usage of message2, you may as well just make its type "const char *" as well.
James Bond
2012-03-19 07:34:16 UTC
Seems all are valid.

I guess you are confused with first arg of printf. It needs a string. It can be string variable or string constant. Commanly we are habituated to give string constant. however above some statements we are sneding message, message2 etc which are variables and are acceptable.
roger
2012-03-19 15:05:07 UTC
They are all valid



Each set prints the same thing.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...