File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes C / C++ and the fly likes Problem in C Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "Problem in C" Watch "Problem in C" New topic
Author

Problem in C

Jatin sachdev
Ranch Hand

Joined: Jan 21, 2010
Posts: 57
Q:What is the output :

main()
{
int var1=4,var2=6;
var2=var2 || var++ && printf("Computer World");
printf("%d %d",var1,var2);
}

the answer coming out is :4 1

My problem is how this is executing...

If you are going to say that this is SHORT CIRCUIT then my question to you is :
How the precedence is being followed in this expression?
Because in this precedence should be like:
++
&&
||

Do consider this also
2+3*4+6 since *(multiply) has higher precedence than + thus we calculate * before +
Same must be applied in the above program if we go by the precedence...
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

Double posted in Beginning Java
http://www.coderanch.com/t/506620/java/java/help-me-solving


luck, db
There are no new questions, but there may be new answers.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
You should know better than to write that sort of code. I presume you have picked up a question from somewhere. Please tell us where, both to avoid copyright problems, and so we shall all know to avoid that website
Remember that C does not have any definite rules about the order of execution, as does Java, so I believe the correct answer is "output undefined". I have seen different results from different C compiler for the same code in the past

You will have to go through the code with a pencil and paper, noting whether "var" is supposed to mean "var1" or "var2". The bit about || being a short-circuit operator is a red herring; the result of executing || and && in code with no side-effects after the || or && should be exactly the same as the results of executing | or &.
I can't remember what printf returns; please remind me.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Also remember what sort of values || and && are supposed to use as operands.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
I earlier wrote: . . . I have seen different results from different C compiler for the same code in the past . . .
That wasn't clear. Sorry. I didn't mean your code, but different code compiled by three compilers giving different results.
Jatin sachdev
Ranch Hand

Joined: Jan 21, 2010
Posts: 57
Sorry for posting the question twice.Very Sorry for that.

main()
{
int var1=4,var2=6;
var2=var2 || var1++ && printf("Computer World");
printf("%d %d",var1,var2);
}


This question is causing me a big headache.
The main problem is in the expression:
var2=var2 || var1++ && printf("Computer World");


There are so many question based on this.These questions come in various recruitment process.
In C:
printf() returns no. of characters it has printed on the screen.
And any non-zero value is considered as TRUE.
Jatin sachdev
Ranch Hand

Joined: Jan 21, 2010
Posts: 57
Please tell me :

Are there jobs in C programming language?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
So have you worked out how you get 1 out of that?

As for jobs, we have a forum where you ought to ask that question as a new thread.
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

There is a problem with that sort of code - it may be deliberately asked in that format an interview just to make it harder to read (not to mention that the code is deliberately confusing). But the reality is that I would never hire someone who wrote code in that format, or who misused features of the language in that way.

While Campbell is correct that different compilers can give different results for the same code, I suspect that this particular code is relying on a common (but not guaranteed) definition of true. If his hints haven't shown you the solution, you may want to do a simple test on your own compiler:

Does seeing the output surprise you? Welcome to the world of C! Do the answers help you understand what is happening in the line you asked about?


The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Bonus question: I returned zero at the end of that program. Given what lines 17 - 21 showed us, what does that mean? What are the implications in the Unix world?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Andrew Monkhouse wrote: . . . you may want to do a simple test on your own compiler . . .
A nice demonstration
Jatin sachdev
Ranch Hand

Joined: Jan 21, 2010
Posts: 57
my problem in this expression is

If we go by the precedence rules of C then var1++ will be executed first then && and || in the last.
But the compiler is executing || first.
Why???

and one more thing in expressions like this :
2+3*4+9
compiler follows precedence because it first calculates * then +.

The main problem with C is its compiler is not very strict.It is not strictly typed language.
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Jatin sachdev wrote:If we go by the precedence rules of C then var1++ will be executed first then && and || in the last.
But the compiler is executing || first.
Why???

Because the || is a sequence point. That is, in order to ensure that there are no side effects, the left side of the || statement will be processed before the right side. Operator precedence would only apply in this case if it affects the outcome of the left operand.

Jatin sachdev wrote:and one more thing in expressions like this :
2+3*4+9
compiler follows precedence because it first calculates * then +.

The compiler must use operator precedence because there are no brackets and no sequence points. Using precedence gives us a clearly defined outcome.

Jatin sachdev wrote:The main problem with C is its compiler is not very strict.

Individual compilers are usually very strict, and where there is any ambiguity in the language the compiler will (in every case I have seen) be very explicit in how it will handle the situation. Your example above follows the rules for C - the operator precedence and the sequence points are used correctly. The possible values for true and false which could potentially cause different results on different compilers is because of a looseness of the language - the compiler will almost certainly be very specific about what it will allow for true and false.

Jatin sachdev wrote:It is not strictly typed language.

True - the fact that we use an integer as a boolean, and later use the boolean result as an integer is very loose typing. Some C aficionados would claim this is a benefit - certainly I have seen some "interesting" code that would not have worked without that feature. Quite often structs are a prime example of this.
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 257

Andrew Monkhouse wrote:
Jatin sachdev wrote:It is not strictly typed language.

True - the fact that we use an integer as a boolean, and later use the boolean result as an integer is very loose typing. Some C aficionados would claim this is a benefit - certainly I have seen some "interesting" code that would not have worked without that feature. Quite often structs are a prime example of this.


Could you clarify what you mean by this in "Quite often structs are a prime example of this"? Are you saying C allows structs to be implicitly converted to bools? Am fairly certain that -

- will fail to compile.


"Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." -- Antoine de Saint-Exupery
Jatin sachdev
Ranch Hand

Joined: Jan 21, 2010
Posts: 57
Thank you for your reply Andrew Monkhouse.....
I think I have to first learn the "PRINCIPLES OF PROGRAMMING LANGUAGES"
How about the book Terrence Pratt, Marvin Zelkowitz??
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Anand Hariharan wrote:
Andrew Monkhouse wrote:
Jatin sachdev wrote:It is not strictly typed language.
True - the fact that we use an integer as a boolean, and later use the boolean result as an integer is very loose typing. Some C aficionados would claim this is a benefit - certainly I have seen some "interesting" code that would not have worked without that feature. Quite often structs are a prime example of this.
Could you clarify what you mean by this in "Quite often structs are a prime example of this"?

Ooops. One mistake I often make when trying to describe solutions to problems is that I often take shortcuts, failing to describe the entire picture of what I can see in my own head. This is (for me) a classic example of my missing some fairly major parts to an overall concept that I can see in my head. My fault for deliberately staying up until midnight to see the meteor shower, and writing a post right on midnight.

What I was thinking of was a union of structs. The unions are so simplistic that I rarely even think of them while thinking about the real problem that I am trying to solve. However the structs themselves can have completely different internal data types. And it is this overlaying of the structs in the same memory region, and the automatic type conversions that happen, that is what I was thinking about.

For the benefit of anyone who is unaware of a union, it is a concept in C that basically states that two or more objects share the same space in memory. A silly example would be:

So - even though we are assigning a number to the short "number" variable in line 14, we are using the char "character" variable in line 15 to see what the character equivalent might be. (There are simpler ways to do this, hence it is a really silly example).

The more interesting things start happening when we start processing data where the type of data changes. An example might be where the first character received in a transmission indicates whether the record is a debit or a credit. There may be different fields in the record based on that type - e.g. a credit record might also indicate tax paid, while a debit record might include reference data. Using a union of 2 structs might make the coding easier to follow.

(I started to write an example to show this, but quickly realized that this was going to end up a way too long post.)
Andrew Monkhouse
author and jackaroo
Marshal Commander

Joined: Mar 28, 2003
Posts: 11404
    
  81

Jatin sachdev wrote:Thank you for your reply Andrew Monkhouse.....
I think I have to first learn the "PRINCIPLES OF PROGRAMMING LANGUAGES"
How about the book Terrence Pratt, Marvin Zelkowitz??

I am unfamiliar with that book, so I cannot make recommendations.

You might want to open a separate topic for this (possibly in the bunkhouse porch).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
Andrew Monkhouse wrote: . . . staying up until midnight to see the meteor shower . . .
It was overcast here every night, so I didn't see anything.

And unions are probably more confusing than pointers. Probably written for economy, in the days when 2kB was a lot of memory.
Anand Hariharan
Rancher

Joined: Aug 22, 2006
Posts: 257

Andrew Monkhouse wrote:What I was thinking of was a union of structs. The unions are so simplistic that I rarely even think of them while thinking about the real problem that I am trying to solve. However the structs themselves can have completely different internal data types. And it is this overlaying of the structs in the same memory region, and the automatic type conversions that happen, that is what I was thinking about.


For the record, the ISO Standard for the C language considers this as undefined behaviour (i.e., it imposes no requirements on the compiler or the runtime for code that does this). The reason is that the layout of data (bit representation) for one of the types in the union could be a trap representation for one of the other types in the union for some hardware.

Notwithstanding that, code such as ...

Andrew Monkhouse wrote:


... is considered idiomatic to ascertain the endianness of particular hardware.


Campbell Ritchie wrote:And unions are probably more confusing than pointers. Probably written for economy, in the days when 2kB was a lot of memory.


You may well be correct about the latter, but I took a loooonng time to wrap my head around pointers (especially the relationship between arrays and pointers) than I did for unions.
 
Don't get me started about those stupid light bulbs.
 
subject: Problem in C
 
Similar Threads
How to read/write directly to/from a class???
Connecting to a script
Getting String input from file
Byte -- what's going on
help me solving this question in C