473,320 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

what is the output and why

hello all,

i would like to know why this code compiles and gives the output

Code 1:
----------
int main(){
printf("String" + 2);
}

Output: ring

Code 2:
----------
int main(){
printf("String", +2);
}

Output: String

I used gcc 3.2 on redhat 8.0 to compile my code

Regards,
Tushar
Nov 13 '05 #1
5 1781
On 4 Aug 2003 21:23:03 -0700, ja*********@yahoo.com (Tushar) wrote:
hello all,

i would like to know why this code compiles and gives the output
They both compile because there is no syntax error in either.

Code 1:
----------
int main(){
printf("String" + 2);
"String" is an array of 7 char (including the terminating \0). In
this context, the expression "String" evaluates to a pointer to the
first char in the array, the S. Adding 2 to this value produces a
pointer to the third char in the array, the r. Since the first
argument to printf is a string, it prints starting at this character
until it reaches the terminating \0.
}

Output: ring

Code 2:
----------
int main(){
printf("String", +2);
Here, it prints the first argument as a string. Since there is no
format specification in this string, it never looks at the second
argument.
}

Output: String

I used gcc 3.2 on redhat 8.0 to compile my code

Shouldn't matter.
<<Remove the del for email>>
Nov 13 '05 #2
Tushar wrote:
I used gcc 3.2 on redhat 8.0 to compile my code


I'd suggest that for the purpose of learning C you add the following
flags to the gcc command line used to compile your programs:

-Wall -Werror

so instead of using:

gcc -o test test.c

you use:

gcc -o test -Wall -Werror test.c

With these flags, your second example would not compile, and you would
have seen a (slightly) helpful message explaining what went wrong.

Regards,

Phil

Nov 13 '05 #3
Mike Wahler <mk******@mkwahler.net> scribbled the following:
Tushar <ja*********@yahoo.com> wrote in message
news:58**************************@posting.google.c om...
Code 2:
----------
#include <stdio.h> int main(){
printf("String", +2);

This is undefined behavior, since there are no
format specifiers, yet you pass an additional
argument. According to the C standard, this program's
behavior could be anything at all.


No, you're wrong. It's perfectly safe to pass *more* arguments to
printf() than it expects. Passing *less*, however, yields undefined
behaviour.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Last year he disrespected me - and then he showed lack of respect."
- Anthony Mason
Nov 13 '05 #4
In <58**************************@posting.google.com > ja*********@yahoo.com (Tushar) writes:
i would like to know why this code compiles and gives the output

Code 1:
----------
int main(){
printf("String" + 2);
}
Hard to answer, since this code invokes undefined behaviour, by calling
printf without a proper declaration in scope. Furthermore, due to the
missing newline character after the last line of output, it need not
produce any output at all.
Output: ring

Code 2:
----------
int main(){
printf("String", +2);
}
The same comments as above.
Output: String


I'll fix the first example and comment on it. The second one is so
easy that, if you can't figure out the answer by yourself, you should
stop messing with C.

#include <stdio.h>

int main()
{
printf("String\n" + 2);
return 0; /* main is a function returning int, right? */
}

A string literal appearing in a normal expression (other than as the
argument of sizeof) is replaced by a pointer to its first char, 'S' in
our case. You're adding 2 to this pointer, obtaining a pointer pointing
2 char's past 'S', i.e. to 'r'. This pointer is passed to printf as its
argument, which interprets it as its format string and behaves
accordingly. In other words, your printf call is equivalent to
printf("ring\n"), which explains the observed behaviour.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #5
In <3f***********************@mercury.nildram.net> Philip Willoughby <pg***@doc.ic.ac.uk> writes:
Tushar wrote:
I used gcc 3.2 on redhat 8.0 to compile my code


I'd suggest that for the purpose of learning C you add the following
flags to the gcc command line used to compile your programs:

-Wall -Werror

so instead of using:

gcc -o test test.c

you use:

gcc -o test -Wall -Werror test.c

With these flags, your second example would not compile, and you would
have seen a (slightly) helpful message explaining what went wrong.


The two programs contain the same number of bugs (undefined behaviour +
gratuitous reliance on implementation-defined behaviour); there is nothing
special about the second one.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Glutinous | last post by:
Trying to learn php, and came across =& as in $form =& $HTTP_POST_VARS; I can't find any reference to =&, with no success in searching for a definition (as though it's _so_ obvious it...
9
by: Sims | last post by:
Hi, I recall a function that would tell me how long it took to generate an output. But for the life of me I cannot remember it. Dow anybody know it? Or do I have to write something myself,...
58
by: Jeff_Relf | last post by:
Hi Tom, You showed: << private const string PHONE_LIST = "495.1000__424.1111___(206)564-5555_1.800.325.3333"; static void Main( string args ) { foreach (string phoneNumber in Regex.Split...
7
by: Neil Zanella | last post by:
OK, this time the compiler's got me a little bit puzzled, simply because it is doing something I am not expecting. My understanding, according to the documentation of std::vector<>::resize(), is...
2
by: yee young han | last post by:
I need a fast data structure and algorithm like below condition. (1) this data structure contain only 10,000 data entry. (2) data structure's one entry is like below typedef struct _DataEntry_...
24
by: kalamantina | last post by:
#include "stdafx.h" #include <stdio.h> #define output( x ) printf( #x "\r\n" );fflush( stdout ) class CMyBase { public: CMyBase() { output( CMyBase() ); f(*this);
1
by: aboood | last post by:
Hi guys Could any one tell me what does that code do please? in pseudo-code #include <fstream.h> #include <iostream.h> bool differsByOneDigit ( int , int ); void outputResults ( ofstream & ,...
23
by: mahesh | last post by:
Hi all, I have following code that is supposed to increase the power by specified value. int main() { system("cls"); int i, exponent; double base; double new_base=0.0;
0
by: Philluminati | last post by:
I have a Perl SOAP Server which returns this SOAP Message when invoked: <?xml version="1.0" encoding="UTF-8"?><soap:Envelope xmlns:xsi="http:// www.w3.org/2001/XMLSchema-instance"...
69
by: Yee.Chuang | last post by:
When I began to learn C, My teacher told me that pointer is the most difficult part of C, it makes me afraid of it. After finishing C program class, I found that all the code I wrote in C contains...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.