home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!ukma!netnews.louisville.edu!starbase.spd.louisville.edu!dsembr01
- From: dsembr01@orion.spd.louisville.edu (Darren S. Embry)
- Subject: QUESTION: TRICKS USING THE ? : OPERATOR
- Sender: news@netnews.louisville.edu (Netnews)
- Message-ID: <dsembr01.725056046@starbase.spd.louisville.edu>
- Date: Tue, 22 Dec 1992 20:27:26 GMT
- Nntp-Posting-Host: orion.spd.louisville.edu
- Organization: University of Louisville
- Lines: 77
-
-
- Okay, here are a couple of interesting and maybe useful tricks I discovered
- that involve the trinary ? : operator:
-
- 1) Using it as a rudimentary if-else statement:
-
- (2*3==6)
- ? printf ("TRUE")
- : printf ("FALSE");
-
- as a substitute for
-
- if(2*3=6)
- printf("TRUE");
- else
- printf("FALSE");
-
- 2) Nesting the ? : operator, as in the example below:
-
- a?(b?c:d):e can be written as a?b?c:d:e
- a?b:(c?d:e) can be written as a?b:c?d:e
-
- I discovered that both of these work using gcc and cc. Here's a test program
- I produced and here's the output:
-
- ------------------------------------------------------ test.c ----------------
- #include<stdio.h>
-
- main()
- {
-
- (2*3==6)
- ? printf("\n---TRUE---\n")
- : printf("\n---FALSE---\n") ;
-
- printf("%d %d\n",1?1?1:2:3,1?(1?1:2):3);
- printf("%d %d\n",1?0?1:2:3,1?(0?1:2):3);
- printf("%d %d\n",0?1?1:2:3,0?(1?1:2):3);
- printf("%d %d\n",0?0?0:2:3,0?(0?1:2):3);
-
- printf("%d %d\n",1?1:1?2:3,1?1:(1?2:3));
- printf("%d %d\n",1?1:0?2:3,1?1:(0?2:3));
- printf("%d %d\n",0?1:1?2:3,0?1:(1?2:3));
- printf("%d %d\n",0?1:0?2:3,0?1:(0?2:3));
-
- printf("%d %d\n", 1?0:1?2:3,1?0:(1?2:3));
-
- }
- ----------------------------------------------------- end of test.c --------
-
- ----------------------------------------------------------- output ----------
- ---TRUE---
- 1 1
- 2 2
- 3 3
- 3 3
- 1 1
- 1 1
- 2 2
- 3 3
- 0 0
- ---------------------------------------------------- end of output ---------
-
- Now, here are a couple of questions that you must answer:
-
- 1) Is this valid ANSI or K&R C?
- 2) Does it work this way on other compilers for other systems?
- 3) Is this recommended?
-
- I would appreciate lots of answers, and any objections to using this.
-
- Thanks in advance,
- --
- ---->8------ Darren Embry --- dsembr01@starbase.spd.louisville.edu -----8<----
- o o This is the Internet. This is a .signature. This is the 1990's. You
- \____/ know what to do. This sentence is the implied disclaimer. You know
- where to direct flames.
-