Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

66%
+2 −0
Q&A Tips for golfing in C

Use pointer arithmetic and \0 with string literals In C, strings are just zero-terminated character arrays, which means you can play tricks with pointer arithmetic. For example, the line char*s=a...

posted 2y ago by celtschk‭

Answer
#1: Initial revision by user avatar celtschk‭ · 2021-11-09T11:11:25Z (over 2 years ago)
# Use pointer arithmetic and `\0` with string literals

In C, strings are just zero-terminated character arrays, which means you can play tricks with pointer arithmetic. For example, the line
```
char*s=a<2?"":"s";
```
can be replaced with
```
char*s="s"+(a<2);
```

Note that you also can use zero bytes inside string constants, which may also help saving a few bytes. For example, if `n` is a number from 0 to 3, instead of:
```
char*s[]={"zero","one","two","three"};puts(s[n]);
```
you can write
```
char*s="zero\0.one\0..two\0..three";puts(s+6*n);
```
Note that the dots are just dummy characters so that the actual strings start at multiples of 6 characters. One may get rid of them at the cost of more complicated arithmetic:
```
char*s="zero\0one\0two\0three";puts(s+4*n+!!n);
```
Whether you save more characters in the string literal than adding to the expression of course depends on the specific strings (and on how often you use that expression in the code).
Note also that if it is the only use of `s`, you may shorten the code further, since unlike array definitions, string literals can be used inline:
```
puts("zero\0one\0two\0three"+4*n+!!n);
```