0

I don't understand why the output is only Warren. And what does switch(money,money*2) mean?

#include<stdio.h>
#define L 10
void main(){
     auto money=10;
     switch(money,money*2){
        case L: printf("William");
               break;
        case L*2: printf("Warren");
               break;
        case L*3: printf("Carlos");
               break;
        case L*4: printf("Inqvar");
               break;
        default: printf("Lawrence");
     }
}
kev
  • 21
  • 3
  • "I don't understand why the output is only Warren" suggests that you believe there *could* be more than one name for output; that's not possible with `break`s in each `case`. – ChiefTwoPencils Mar 10 '16 at 03:08
  • Don't use `auto` in C code. It is essentially pointless. In C++11 or later, it is used wholly differently — your code might be OK as C++11 code, but then the language tag is all wrong. See also [What should `main()` return in C and C++](http://stackoverflow.com/questions/204476/). – Jonathan Leffler Mar 10 '16 at 03:51

2 Answers2

2

switch(money, money*2) is as good as switch(money*2) in this case since the first expression money before the , doesn't do anything.

Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17
  • "...is as good as as..." should probably be ..."is equivalent to...". – ChiefTwoPencils Mar 10 '16 at 03:21
  • @AshishAhujaツ, they have a habit of disappearing sometimes; someone felt guilty I suppose... – ChiefTwoPencils Mar 10 '16 at 03:23
  • @ChiefTwoPencils, yup, I agree. But this is rare. I've seen people voting on my posts and then reversing it, but I haven't seen someone reverse a downvote till now. – Box Box Box Box Mar 10 '16 at 03:23
  • @AshishAhujaツ, that seems contradictory; perhaps I am misunderstanding you. I often *hope* I'm able to reverse a down vote because many times it's there to affect change. I do agree, tho, that many don't maintain their votes well enough and as a result there are un-founded/corrected votes (those that persist regardless of edits). – ChiefTwoPencils Mar 10 '16 at 06:09
  • @ChiefTwoPencils, I agree that it is useful. I have myself reversed a few downvotes (and upvotes too), when I see that the post I have voted on has changed, and the DV or UV has become invalid. But many times after voting, I never come back to it. And yes, I meant to say that I have seen very few downvotes reversed; I ain't saying that it is a bad feature. – Box Box Box Box Mar 10 '16 at 06:13
0

Short Answer: First Expression 1 is evaluated, then Expression 2. But the value of expression 2 is returned. So this is basically equivalent to:

switch (money * 2)

Long Answer: This is a duplicate of What does the comma operator , do in C?

Community
  • 1
  • 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67