[C] String Literal Concatenation, why does C support this?

news/2026/1/21 23:31:52/文章来源:https://www.cnblogs.com/profesor/p/19514336

 

printf("elaine" "benes" "\n");

 

In C, what you're seeing isn't actually "separate arguments"—it’s a feature called String Literal Concatenation.

When the C compiler encounters two or more string literals adjacent to each other (separated only by whitespace or comments), it automatically joins them into a single null-terminated string during the translation phase.

To the printf function, your code looks exactly like this:

printf("elainebenes\n");

Why does C support this?

This feature was introduced for several practical reasons:

  • Breaking Up Long Strings: Without this, if you had a very long sentence, you would have to write it on one massive line or use the messy backslash line-continuation character (\). With concatenation, you can neatly align your text:

    C
     
    char *message = "This is a very long string ""that spans multiple lines ""for better readability.";
    
  • Macro Expansion: It is incredibly useful when working with the preprocessor. You can combine a hardcoded string with a defined macro:

    C
     
    #define VERSION "2.0"
    printf("Software Version: " VERSION "\n");
    // Compiler sees: "Software Version: 2.0\n"
    
  • Formatting Source Code: It allows developers to keep their source code within a certain column width (like 80 or 100 characters) without affecting the output of the program.

How the Compiler Processes It

The concatenation happens during Translation Phase 6 of the compilation process, which is after preprocessing but before the actual semantic analysis.


Important Distinction

Be careful not to confuse this with passing multiple arguments to printf using commas.

  • printf("A" "B"); // Valid: One argument "AB".

  • printf("A", "B"); // Warning/Error: Two arguments, but the first (the format string) doesn't have a %s to handle the second.

Would you like to see how this feature is commonly used in complex printf format strings or with #define macros?

 

 

When you start combining string concatenation with macros, it transforms from a simple "cleanup" tool into a powerful way to manage configuration and debugging.

Here are the two most common advanced use cases:

1. The Macro "Glue" Pattern

This is widely used in systems programming. By using the preprocessor, you can inject version numbers, file paths, or specific tags into a message without manually typing them every time.

C
 
#define APP_NAME "SystemMonitor"
#define LOG_LEVEL "ERROR"// The compiler glues these three pieces into: "[SystemMonitor] ERROR: Connection Failed"
printf("[" APP_NAME "] " LOG_LEVEL ": Connection Failed\n");

2. Formatting Long printf Strings

If you are building a complex output (like a table header or a multi-line help menu), putting it all on one line is a nightmare to maintain. You can use concatenation to make the code look like the output:

C
 
printf("ID   | Name       | Status\n""-----|------------|----------\n""%04d | %-10s | %s\n", 101, "Elaine", "Active");

How it works "Under the Hood"

It is helpful to visualize where this happens in the C Build Process. The compiler doesn't just jump from your code to an executable; it goes through several "Translation Phases." String literal concatenation happens very late in the process, specifically in Phase 6.

Phase Action
Phase 3 Decomposes source into preprocessing tokens (including string literals).
Phase 4 Executes Macros (replaces VERSION with "2.0").
Phase 6 Adjacent string literals are concatenated into a single token.
Phase 7 The single string is analyzed and compiled into machine code.

A Common "Gotcha"

Since the compiler only needs whitespace between strings to join them, it's easy to accidentally join strings if you forget a comma in an array:

C
 
char *names[] = {"Jerry","George"   // Forgot a comma here!"Kramer","Elaine"
};// Result: {"Jerry", "GeorgeKramer", "Elaine"}

Would you like to see how to use the "Stringification" operator (#) to turn variable names themselves into concatenated strings for debugging?

 

To take string concatenation to the next level, C programmers use the Stringification Operator (#).

This preprocessor trick converts a macro argument into a string literal. When combined with adjacent string concatenation, it allows you to write extremely helpful debugging tools that "know" the names of the variables they are printing.

The "Print Variable Name" Trick

Imagine you want to print a variable’s name and its value. Usually, you'd have to type the name twice. With concatenation, you can automate it:

C
 
#define DEBUG_INT(var) printf(#var " = %d\n", var)int elaine_score = 150;
DEBUG_INT(elaine_score); 

How the compiler handles this:

  1. Macro Replacement: The #var becomes "elaine_score".

  2. Concatenation: The compiler sees "elaine_score" adjacent to " = %d\n".

  3. Result: It joins them into a single format string: printf("elaine_score = %d\n", elaine_score);.


Breaking Down the C Translation Phases

As mentioned earlier, this all happens in Phase 6. It is helpful to see exactly where this fits in the lifecycle of your code, from a text file to an executable.

Phase Purpose Example
Phases 1-3 Cleanup & Tokenizing Removes comments, handles line splicing.
Phase 4 Preprocessing Expands #define and #include.
Phase 6 Concatenation "Hello " "World" becomes "Hello World".
Phase 7 Compilation Translates the result into assembly/machine code.

Why doesn't every language do this?

Modern languages like Python or Java typically use the + operator (e.g., "a" + "b") to join strings. C doesn't do this because:

  1. In C, strings are often just pointers (char*). Adding two pointers (ptr + ptr) is mathematically invalid in C.

  2. Efficiency: This concatenation happens at compile-time. There is zero performance cost when the program actually runs, whereas using a function like strcat() happens at run-time and consumes CPU cycles.

A Pro Tip: The "Space" Requirement

Note that you need at least one character of whitespace (space, tab, or newline) between the strings.

  • "benes""\n" is technically valid.

  • "benes" "\n" is much more readable and preferred.

Would you like to see how this is used with the __FILE__ and __LINE__ macros to create a custom error logger?

 

Combining the __FILE__ and __LINE__ macros with string concatenation is a standard "pro move" in C. It allows you to create error messages that tell you exactly where they happened in the source code.

The __FILE__ macro expands to a string literal of the current filename, and __LINE__ expands to the current line number. However, since __LINE__ is an integer, we have to use a "double-macro" trick to turn it into a string so it can be concatenated.

The "Trace" Macro

Here is how you build a logger that automatically tags your file and line number:

C
 
#define STR(x) #x
#define TOSTR(x) STR(x)// __FILE__ is a string, TOSTR(__LINE__) becomes a string
// The compiler "glues" them all together into one format string.
#define LOG_ERR(msg) printf("[" __FILE__ ":" TOSTR(__LINE__) "] ERROR: " msg "\n")int main() {LOG_ERR("The soup is too cold!"); // Output: [main.c:8] ERROR: The soup is too cold!return 0;
}

Why this is powerful

By using concatenation here:

  • Zero Runtime Overhead: The final string "[main.c:8] ERROR: The soup is too cold!\n" is constructed by the compiler. The program doesn't waste time joining strings while it's running.

  • Clean Syntax: You don't have to pass %s and %d arguments to every single print statement; the metadata is baked into the format string itself.


The Big Picture: Where this happens

To wrap up our deep dive, it helps to see exactly where this "gluing" happens in the life of a C program. String concatenation is one of the final steps of preparing the source code before it is turned into actual assembly language.

Phase What Happens Result for our Macro
Phase 4 Preprocessor expands LOG_ERR printf("[" "main.c" ":" "8" "] ERROR: " "msg" "\n")
Phase 6 Concatenation printf("[main.c:8] ERROR: msg\n")
Phase 7 Compilation Code is converted to machine instructions.

Summary of Benefits

  • Readability: Breaks long strings across multiple lines.

  • Maintainability: Allows macros to inject information seamlessly.

  • Performance: All the work is done at compile-time, making the resulting executable faster and smaller.

Would you like to explore how this compile-time logic differs from "Runtime" string functions like strcat or sprintf?

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1196670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【计算机毕业设计案例】基于springboot+vue的javaweb宝贝回家走失儿童报备基于springboot的走失儿童认领与登记系统(程序+文档+讲解+定制)

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围:&am…

EI会议检索征稿!!!2026年智能感知与自主控制国际学术会议(IPAC 2026)

会议亮点抢先看: 1.已通过IEEE出版社,EI稳定检索 2.IEEE Fellow、杰青助力,佛山大学主办 3.大会设立评优评奖环节,现场颁发大会证书 ✔IPAC 2026已上线IEEE官网: ✔经大会评审的优秀论文,将有机会直接推…

MC-SMoE: MoE 模型压缩方案

Merge, Then Compress:用路由策略解开高效 SMoE 的压缩之谜 读完论文先给你结论 这篇文章解决的核心问题是: SMoE 很强但太占内存且专家冗余严重 。作者从路由策略里“挖线索”,提出 先合并再压缩 的两阶段方案 MC-SMoE 。它通过路由激活频…

MCP学习笔记

MCP学习笔记 最近由于组织架构变动,负责AI相关工具建设,学习一下MCP相关的知识 1、MCP介绍 1.1、什么是MCP MCP(Model Context Protocol,模型上下文协议)是 Anthropic 开发的一个开放标准协议,用于让 AI …

AI大模型开发入门到精通:一本助你转型的必备书籍

文章介绍了《AI大模型开发之路》一书,为转型AI大模型开发工程师提供全面指导。内容涵盖Python编程、机器学习基础、Transformer模型原理、API调用实战、LangChain框架应用,以及项目部署等全流程。通过系统化学习路径,从理论到实践帮助读者掌握…

UE5 C++(43):用 timeLine 实现开关门

(222)概述:本节里会为 timeLineActor 继续添加盒体碰撞组件,还有一个门,当 character 角色来,发生碰撞时,让那个门(静态网络体组件)旋转。碰撞的方面的设置,在…

HC-SMoE: MoE Expert 合并压缩方案解读

Retraining-Free Merging of Sparse MoE via Hierarchical Clustering(HC-SMoE)长文解读 一句话总结 这篇论文要解决的是 SMoE 模型太大、专家冗余严重 的问题,提出了一个 不需要再训练 的专家合并框架 HC-SMoE,用 专家输出的相…

基于SpringBoot+Vue校园跑腿网站的设计与实现

博主主页:一点素材 博主简介:专注Java技术领域和毕业设计项目实战、Java微信小程序、安卓等技术开发,远程调试部署、代码讲解、文档指导、ppt制作等技术指导。 技术范围:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬…

IPO投资策略:如何评估新上市公司

IPO投资策略:如何评估新上市公司 关键词:IPO投资策略、新上市公司评估、财务分析、行业前景、管理团队 摘要:本文聚焦于IPO投资策略,旨在深入探讨如何全面、科学地评估新上市公司。通过对背景知识的介绍,阐述核心概念及联系,剖析核心算法原理与操作步骤,运用数学模型和公…

基于SpringBoot+Vue校园足球俱乐部管理系统的设计与实现

博主主页:一点素材 博主简介:专注Java技术领域和毕业设计项目实战、Java微信小程序、安卓等技术开发,远程调试部署、代码讲解、文档指导、ppt制作等技术指导。 技术范围:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬…

导师严选2026 TOP10 AI论文工具:专科生毕业论文写作全测评

导师严选2026 TOP10 AI论文工具:专科生毕业论文写作全测评 2026年AI论文工具测评:为何值得一看? 随着人工智能技术的不断进步,AI写作工具在学术领域的应用越来越广泛。对于专科生而言,撰写毕业论文不仅是学业的重要环节…

Linux OOM killer 评分系统的演变及分数优先级详解

📊 OOM 分数优先级详解 🎯 OOM 评分系统的演变 在 Linux 内核中,OOM Killer 的评分系统经过了演进: 历史版本: oom_adj(旧版,范围:-16 到 15) 内核版本 2.6.11-2.6.36…

降AI率必备!6款免费工具亲测,学生党轻松降80%,论文AI检测一次过

最近身边不少同学都在发愁——论文AI率太高。明明自己认真改过好几遍,系统一查还是提示AIGC爆表,导师看一眼就摇头。其实现在用AI辅助写论文确实方便,但怎么降低ai率、让内容更自然,才是真正过关的关键。 我这段时间亲测了十几款…

AI Agent实战指南:程序员必学大模型应用,从概念到商业布局,值得收藏

人工智能体(AI Agent)已从技术概念跃入商业现实,迎来爆发时刻。作为大语言模型驱动的智能系统,AI Agent能自主感知、决策与执行,从"辅助工具"向"核心生产力"跃迁。OpenAI、Monica、阿里巴巴等科技大厂纷纷布局&#xff0…

基于SpringBoot+Vue学校物资采购系统的设计与实现

博主主页:一点素材 博主简介:专注Java技术领域和毕业设计项目实战、Java微信小程序、安卓等技术开发,远程调试部署、代码讲解、文档指导、ppt制作等技术指导。 技术范围:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬…

AI率过高别慌!这6个免费降AI工具亲测有效,学生党拯救论文指南

最近身边不少同学都在发愁——论文AI率太高。明明自己认真改过好几遍,系统一查还是提示AIGC爆表,导师看一眼就摇头。其实现在用AI辅助写论文确实方便,但怎么降低ai率、让内容更自然,才是真正过关的关键。 我这段时间亲测了十几款…

Balanced 01-String

Balanced 01-String 题目描述 小苯有一个长度为 $n$ 的字符串 $s$,只包含字符 $\texttt{0}$、$\texttt{1}$ 和 $\texttt{?}$。 他定义一个 $01$ 字符串是平衡的,当且仅当字符串中所有相邻两个字符相同的对数(即满足…

AI大模型学习全攻略:零基础入门、35岁转行可行性与就业前景

文章探讨35岁转行学习AI大模型的可行性、零基础入门可能性和行业前景。指出35岁转行完全可行,零基础学习者可通过丰富资源掌握技能。AI大模型行业前景广阔,需求增长。文章提供了系统学习路线,包括基础理解、API应用开发、应用架构实践和私有化…

基于SpringBoot+Vue一鹿租车公司车辆管理系统的设计与实现

博主主页:一点素材 博主简介:专注Java技术领域和毕业设计项目实战、Java微信小程序、安卓等技术开发,远程调试部署、代码讲解、文档指导、ppt制作等技术指导。 技术范围:SpringBoot、Vue、SSM、HLMT、Jsp、PHP、Nodejs、Python、爬…

D6 707.设计链表

707 设计链表(力扣:https://leetcode.cn/problems/design-linked-list/ 条件: 见原题链接 Tips: 代码: 点击查看代码 struct ListNode{int val;ListNode* prev;ListNode* next;//使用初始化列表ListNode( int num…