?
Solved

Basic C question

Posted on 2011-10-23
20
Medium Priority
?
646 Views
Last Modified: 2012-05-12
I have a question about printf and scanf. Basically it is this program:

#include <stdio.h>
#define STOP 0
int main()
{
   int counter;
   int startPoint;
   printf(“=====Countdown Program =====\n”);
   printf(“Enter a positive integer: “);
   scanf(“%d”,  &startPoint);
   for(counter = startPoint; counter >= STOP; counter--)
  printf(“%f\n”, counter);

}
Now replacing the line printf(“%f\n”, counter); with each of the following lines and running it:

a)      printf(“%c\n”, counter + “A”);
b)      printf(“%X\n”, counter + &(“A”));
c)      printf(“%f\n”, counter);

I don't understand the output of each one, and what is happening. HELP please!!!
0
Comment
Question by:dearCode
  • 7
  • 6
  • 5
  • +1
19 Comments
 
LVL 9

Accepted Solution

by:
raysonlee earned 500 total points
ID: 37015889
%c is character
%x is Hexadecimal
%f is float
Refer to http://www.codingunit.com/printf-format-specifiers-format-conversions-and-formatted-output for more details.
0
 

Author Comment

by:dearCode
ID: 37016019
I know that and I even saw the link you provided before. If you run the program it is going to print out messy stuff. SO the question is why are they doing that!!! HELP
0
 
LVL 9

Expert Comment

by:raysonlee
ID: 37016096
What exactly you want to achieve?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 2

Expert Comment

by:xeltek
ID: 37016146
Hi,
what kind of output you want to have?
printf, it means print with format. and if defines rules to format the string.
you need to just follow the rule.

xeltek
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 1500 total points
ID: 37016378
>> If you run the program it is going to print out messy stuff.

That sounds reasonable for the code you try to run.

The problem is that you're in the domain of undefined behavior, so anything can happen. Including what you're seeing.

This also means that the output cannot be explained, unless you have a deeper knowledge about the specific compiler/platform that you used to get the result you got.

Try just doing :

        printf("%d\n", counter);

That should work better.
0
 

Author Comment

by:dearCode
ID: 37052041
I've requested that this question be deleted for the following reason:

it has been posted for a long time, and no good answers
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 37052042
>> it has been posted for a long time, and no good answers

It has been posted since less than a week, and there are several expert replies (all posted within a few hours of you asking the question) you haven't even responded to.

If those answers aren't "good", then please clarify how they could have been better.

I can assure you that your question has been answered - but maybe you need further clarification. If that's the case, please ask us, and we'll be glad to provide it.
0
 

Author Comment

by:dearCode
ID: 37053458
I think my question is clear enough. And so far all the answers are WRONG. It seems to me that they just wanted to post anything. If they take my peice of code and run it, they will know what I'm talking about here. I'll give you an example for part a), when I run it, it gives all these Ansi characters, And since as you said it has been a week, I actually figured it out myself. And it wasn't easy. But if you could figure  it out for part b) and c) that would be great.
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 1500 total points
ID: 37053602
>> And so far all the answers are WRONG.

No, they're not. Maybe you didn't expect the answers given, but they're right nevertheless.


>> And since as you said it has been a week

It has been a week, because you never responded to any of the responses, which were posted less than 5 hours after your question.


>> I actually figured it out myself.

There's nothing to figure out really, other than that you're dealing with undefined behavior. If you run the code on a different platform (or even on the same platform under different circumstances), it's likely to give you different output.

It is not a good thing to rely on undefined behavior. Nor is it particularly interesting to try to understand it.

Specifically :

In the first two cases, you are trying to print a memory address with the wrong format specifiers. And on top of that, the memory address is potentially an invalid address, and very likely out of bounds.

In the last case, you're trying to print an integer value using the floating point format specifier. This too is invalid.


So : in short : the code you posted is NOT covered by the C standard - there is NO guarantee how it will behave. So, do NOT use this kind of code.
0
 
LVL 9

Expert Comment

by:raysonlee
ID: 37053652
I agree with Infinity08, I still don't know what dearCode wants to achieve with the codes in question. If dearCode figured out the "correct" answer, please post your solution out.
0
 

Author Comment

by:dearCode
ID: 37053827
Ok, still you don't get what I'm saying. For part a) that figured out, if you take out the counter, so it would be printf(“%c\n”, “A”); this prints the address of the "String" A. In my case the address was 4020db. I KNOW that the address would be different depending on the computer you are using. NOW the bianry representation of 4020db is 10000000010000011011011. Since a character is represented by 8 bits just the first 8 bits are taken which are 11011011. In decimal this is 219, which is the ANSI character Û. since we are adding 1 each time in the loop because of the counter. if we input the counter as 5, it prints the ANSI characters that have the decimal values 224, 223,222,221,220,219. SO can you tell me what part b) EXACTLY does???
0
 
LVL 53

Assisted Solution

by:Infinity08
Infinity08 earned 1500 total points
ID: 37053860
>> Ok, still you don't get what I'm saying.

I think you're not getting what I'm saying ;)

What you figured out is just how your platform deals with the undefined behavior of that code. Nothing more.

It is not a simple matter of a different address of the string literal "A". The undefined behavior I was referring to is more fundamental. Namely (as I mentioned before) the incorrect use of format specifiers (ie. not matching to the types of the arguments being passed).

Specifically, the C standard states :

        "If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined."

The correct argument type corresponding to %c, is an int.
The correct argument type corresponding to %X, is an unsigned int.
The correct argument type corresponding to %f, is a double.

In none of the three presented cases, the correct argument type was used, so all three cases have undefined behavior.

Turn it however you like, but that is the only valid answer to your question.
0
 

Author Comment

by:dearCode
ID: 37053873
I've requested that this question be closed as follows:

Accepted answer: 0 points for dearCode's comment http:/Q_27411399.html#37053827
Assisted answer: 0 points for dearCode's comment http:/Q_27411399.html#37053458

for the following reason:

No one gave the answer I want
0
 

Author Comment

by:dearCode
ID: 37053871
NO, you are completely wrong about the question and about the argument types:
The correct argument type corresponding to %c, is a char.
The correct argument type corresponding to %X, is a hexdecimal number.
The correct argument type corresponding to %f, is a FLOAT. %lf is for doubles!!!!!!!!!!!

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 37053874
>> No one gave the answer I want

I'm sorry. I wasn't aware this was a riddle.

You were given the correct answer. Maybe it wasn't what you expected, but it's correct nevertheless.

If you choose to ignore the expertise that you asked for, that's your decision. But the posts you have currently accepted are incorrect, and should not be stored in the answer database. Hence my objection.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 37053885
>> The correct argument type corresponding to %c, is a char.

No. From the standard :

        "c     If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written."


>> The correct argument type corresponding to %X, is a hexdecimal number.

No. From the standard :

        "o,u,x,X     The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X) in the style dddd;"


>> The correct argument type corresponding to %f, is a FLOAT. %lf is for doubles!!!!!!!!!!!

No. From the standard :

        "f,F     A double argument representing a floating-point number is converted to decimal notation in the style [-]ddd.ddd"



Look, I sense that you don't trust my expertise, and that's your loss. But I think it would be a good idea to reconsider :)
0
 
LVL 9

Expert Comment

by:raysonlee
ID: 37054880
dearCode,

If you want to print the character A to E, you should do it like this:
main()
{
int counter;
for (counter=0; counter<5; counter++)
printf("%c\n", (char) ('A'+counter));
}

If you want to print the hexadecimal values of A to E, then use
printf("%x\n", (char) ('A'+counter));

If you want to print the value of counter, use
printf("%d", counter);
or in floating point format
printf("%f", (float) counter);

You are getting messy output, simply because the commands are not used correctly.
0
 
LVL 9

Expert Comment

by:raysonlee
ID: 37054923
By the way, you asked what the command
  printf(“%X\n”, counter + &(“A”));
does.
It will take the memory address of the string "A", add counter will advance the memory address pointer by  "counter" times, then print the result in hexadecimal format. Depends on your system's word size, an increase of 1 in counter may advance the memory address by 1 byte in 8 bit system, 2 bytes in 16 bit system, 4 bytes in 32 bit system. As the memory location is allocated dynamically every time you run the program, you will get unpredictable result as Infinity08 said.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 37055154
>> you will get unpredictable result as Infinity08 said.

That's not the big problem with this code. A changing memory address is not undefined behavior - it's simply an implementation detail.
The undefined behavior, is because the argument types are not matched up with the format specifiers.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Author Cited: Konstantinos Dimopoulos URL Cited From: Article from Indie Games: http://indiegames.com/2012/07/browser_game_pick_the_grid.html The Grid (http://codeelf.com/games/grid/) is the sort of game I haven't played in over 10 years. It is …
Recently, in one of the tech-blogs I usually read, I saw a post about the best-selling video games through history. The first place in the list is for the classic, extremely addictive Tetris. Well, a long time ago, in a galaxy far far away, I was…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses
Course of the Month14 days, 18 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question