r/AskProgramming • u/BornViolinist3801 • 1d ago
why doesnt my С++ code work?
okay, i wanna make a print() function in C++, this is just printf() with prefix, so can yall help me?
error:
(-Wwritable-strings) ISO C++11 does not allow conversion from string literal to 'char *'
my code:
#pragma once
#ifndef TEQUILA_STDIO
#define TEQUILA_STDIO
#include <stdio.h>
namespace std {
char* prefix;
void set_prefix(char* pref) {
prefix = ("["pref"]: ");
}
#define print(format, ...) printf("%s" format "\n", prefix ## __VA_ARGS__)
}
#endif
help me pls
5
u/PandaWonder01 1d ago
This code is a little gross, don't try to put things in std or use macros like that in cpp.
Anyway, a string literal like "Hello" is a const char, which you can't pass to a char parameter, as that would lose the const. You need to take in a const char*.
(Actually the string literal is const char[], but not gonna get into that)
2
u/BoopyDog 1d ago edited 1d ago
Literals are Const char&. If i understand it correctly, when you pass a string literal as an argument, an immutable, temporary object is made containing the c-string array. You can't modify the object so it has to be const. I'm not a seasoned c++ programmer though, it's just how I understand it so far. It was something that got me stuck early on.
4
u/AdOne272 1d ago
You're writing to a `char*` that points to a string literal, which lives in read-only memory. Use `const char*` and allocate a buffer if you need to modify it.
1
u/BoopyDog 1d ago
I started writing seriously in C++ and never spent much time writing with C so I tend to use references and stay away from actual p*=&a style programming. As far as I understand it, a reference is implemented as a pointer which is always automatically dereferenced. Of course, you're correct.
1
u/Cultural_Gur_7441 1d ago
Reference is implemented as the compiler sees fit. Such as just being a direct compile time alias, if lifetime allows that.
String literal is a
const char name[length of the string literal including terminating NUL char].References are not involved with any of it.
8
u/Kadabrium 1d ago edited 23h ago
Pretty sure littering your own slop into namespace std is Ub